有一个Nullable<T>
结构体,还有另一个静态的Nullable
类,其中包含三个静态方法。
我的问题是,为什么不能将这些静态方法放入静态Nullable
类中的Nullable<T>
结构体中?为什么要在两种不同的类型中定义它们?
还有一个INullable
接口。它是用来做什么的?
有一个Nullable<T>
结构体,还有另一个静态的Nullable
类,其中包含三个静态方法。
我的问题是,为什么不能将这些静态方法放入静态Nullable
类中的Nullable<T>
结构体中?为什么要在两种不同的类型中定义它们?
还有一个INullable
接口。它是用来做什么的?
Is a standard practice with Generics to have class with the same name of your generic class with utility methods related to the generic class. Because when you use a generic class you cant't infer the generics in the type declaration you'll end up with many more characters. Look how it would be if the static methods were placed in the generic class:
Nullable<int?>.Compare(x, Y);
var n = new Tuple<int,string>(10, "Text");
vs
Nullable.Compare(x, Y);
var n = Tuple.Create(10, "Text");
I included Tuple as another example.
Interfaces and base classes are very useful in Generics, and since Nullable<> is struct and structs cannot have a base class, we are left with interfaces. Now here is a possible usage of it.
{
int? a = 10;
long? b = 10L;
Process(a);
Process(b);
}
private static void Process(INullable value)
{
if (value.IsNull)
{
// Process for null ..
}
else
{
// Process for value ..
}
}
public static bool Is<T>(this T variable,Type type) {
if (var != null) {
Type currentType = variable.GetType();
type = Nullable.GetUnderlyingType(type) ?? type;
while (currentType != typeof(object)) {
if (currentType == type) {
return true;
}
currentType = currentType.BaseType;
}
}
return false;
}
nullable
),但实际上它可能是nullable
,因此必须检查是否nullable
。Nullable.GetUnderlyingType(type)
,因为它是一个实用方法。这是实用方法的预期行为,即使它们可重用于任何需要而不必每次都创建实例。