C#中的Explicit和Implicit

implicit和explicit是一对转换操作符
Implicit关键字:用于声明隐式的用户定义类型转换运算符。它可以实现2个不同类的隐式转换 ,提高代码的可读性。
Explicit关键字:声明必须通过转换来调用的用户定义的类型转换运算符。不同于隐式转换。

 1 public class People<T>
 2     {
 3         public string Name { get; set; }
 4         public int Age { get; set; }
 5         public T Data { get; set; }
 6 
 7         public People(string name = "zhangsan", int age = 15)
 8         {
 9             this.Name = name;
10             this.Age = age;
11         }
12 
13         public People()
14         {
15 
16         }
17 
18         public static implicit operator People<T>(int age)
19         {
20             return new People<T>(age: age);
21         }
22         public static implicit operator People<T>(string name)
23         {
24             return new People<T>(name: name);
25         }
26         public static implicit operator String(People<T> p)
27         {
28             return p.Name;
29         }
30         public static implicit operator int(People<T> p)
31         {
32             return p.Age;
33         }
34         public static explicit operator T(People<T> p)
35         {
36             return p.Data;
37         }
38         public static implicit operator People<T>(T t)
39         {
40             return new People<T>() { Data = t };
41         }
42 
43     }

使用:

 1   static void Main(string[] args)
 2         {
 3 
 4             People<DateTime> p = new People<DateTime>(name: "zhangsan", age: 15);
 5             int age = p;
 6             string name = p;
 7             People<DateTime> p2 = 16;
 8             People<DateTime> p3 = "lisi";
 9             People<DateTime> p4 = DateTime.Now;
10             object data = (DateTime)p4;
11             
12             Console.ReadKey();
13         }

案例

非空校验

方法的参数非空校验,导致校验很多、非常繁琐,以下代码是个思路

public class NotNull<T>
{
    public NotNull(T value)
    {
        this.Value = value;
    }

    public T Value { get; set; }

    public static implicit operator NotNull<T>(T value)
    {
        if (value == null)
            throw new ArgumentNullException();
        return new NotNull<T>(value);
    }
}
public void DoSomething(NotNull<string> message, NotNull<int> id, NotNull<Product> product)
{
  // ...
}

不需要参数校验了~

posted @ 2019-12-13 13:29  .Neterr  阅读(678)  评论(0编辑  收藏  举报