C# 泛型中的数据类型判定与转换

提到类型转换,首先要明确C#中的数据类型,主要分为值类型和引用类型:

1.常用的值类型有:(struct)

整型家族:int,byte,char,short,long等等一系列

浮点家族:float,double,decimal

孤独的枚举:enum

孤独的布尔:bool

2.常用的引用类型有:

string,class,array,delegate,interface

值得注意的是,无论是值类型还是引用类型,在C#中都派生于object,没错,这家伙就是万恶之源!

正是因为有了这一特性,于是我们才能通过装箱和拆箱愉快地将这些数据类型在值类型,object,引用类型间反复横跳。

当然了,无论是装箱和拆箱,对于性能都是有消耗的,不到万不得已的时候尽量不要用(虽然我才不管这些,只要我用的爽就行了233)

 

虽然一般不提倡用object类型作为函数参数,取而代之使用泛型成为首选,那么如何判断泛型参数的具体数据类型并进行有效转换呢?

比如下面的例子:

1 [System.Serializable] 2 public struct Property<T> where T : struct 3 { 4 public string Label { get; } 5 public T Value { get; } 6 public PropertyType Type { get; } 7 public Property(string label, T value, PropertyType type = PropertyType.Sub) 8 { 9 Label = label; 10 Value = value; 11 Type = type; 12 } 13 14 public static Property<T> operator +(Property<T> a, Property<T> b) 15 { 16 var prop = new Property<T>(); 17 if (a.Label == b.Label && a.Type == b.Type) 18 { 19 //怎么知道这个值到底是int还是float... 20 } 21 return prop; 22 } 23 }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpdffg.html