c#隐式转换

Posted on 2012-06-13 13:16  leon_ALiang  阅读(505)  评论(0编辑  收藏  举报

The implicit keyword is used to declare an implicit user-defined type conversion operator.

http://msdn.microsoft.com/en-us/library/z5z9kes2(v=vs.71).aspx

之前一直没有用过,最近项目中用到,发现隐式转化还是很有用的,尤其是在代码重构的过程中。

举个简单的例子:

在原先的代码中,某一个数据成员一直是String类型,但由于需求变化,我们需要将用到该数据成员的某些scenario变化为CustomList类型。

这时候我们首先需要实现一个CustomList类型的数据结构,但之前的String类型怎么办呢?

如果没有隐式转化我们就需要使用两种Type来操作同一数据成员或者都使用CustomList但需要对之前所有用到String的操作都做相应的修改,这样显然有很大的工作量且有可能引起其他的bug.

这时候隐式转化就发挥作用了,我们可以在CustomList<String>类中实现String和CustomList的相互转化,而不需要再修改之前的任何地方。

直接上代码了:

 1 public class CustomList : List<String> {
 2 
 3         /// <summary>
 4         /// Initializes a new instance of the <see cref="CustomList"/> class.
 5         /// </summary>
 6         /// <param name="value">The value.</param>
 7         public CustomList(String value) {
 8             Value = value;
 9         }
10 
11         /// <summary>
12         /// Gets or sets the value.  This gets or sets the first value of the
13         /// list.  This is the same value returned by the implicit string casts.
14         /// </summary>
15         /// <value>The value.</value>
16         public String Value {
17             get {
18                 if (Count == 0) {
19                     return default(String);
20                 }
21                 else {
22                     return base[0];
23                 }
24             }
25             set {
26                 if (Count == 0) {
27                     Add(value);
28                 }
29                 else {
30                     base[0] = value;
31                 }
32             }
33         }
34 
35         /// <summary>
36         /// Performs an implicit conversion from <see cref="CustomList"/>
37         /// </summary>
38         /// <param name="val">The val.</param>
39         /// <returns>The result of the conversion.</returns>
40         public static implicit operator String(CustomList val) {
41             if (val == null) return null;
42             return val.Value;
43         }
44 
45         /// <summary>
46         /// Performs an implicit conversion from <see cref="System.String"/>
47         /// </summary>
48         /// <param name="item">The item.</param>
49         /// <returns>The result of the conversion.</returns>
50         public static implicit operator CustomList(String item) {
51             return new CustomList(item);
52         }
53     }

 

Copyright © 2024 leon_ALiang
Powered by .NET 8.0 on Kubernetes