为什么会有 Nullable<T> 结构体和 Nullable 类?

4

有一个Nullable<T>结构体,还有另一个静态的Nullable类,其中包含三个静态方法。

我的问题是,为什么不能将这些静态方法放入静态Nullable类中的Nullable<T>结构体中?为什么要在两种不同的类型中定义它们?

还有一个INullable接口。它是用来做什么的?


1
很好的解释:https://dev59.com/Q2855IYBdhLWcg3wjlKL - Hakunamatata
3
可能是 为什么 Nullable<T> 是一个结构体? 的重复问题。 - Abion47
这不是重复的。 - Cheng Chen
@Abion47 或许你没有理解我的问题。 - Prudhvi
2个回答

7
  1. 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.

  2. 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 .. 
        }
    }
    

我从未见过关于某些泛型类的非泛型类的文章,但通过查看.NET框架中的多个泛型类,我得出了这个结论。您可以查看非泛型类Tuple和Nullable的文档,您会注意到它们被提及为同一类。 Tuple Nullable - AL - Lil Hunk

1
它们被写成一个独立的类,因为这些方法是实用方法,旨在随时在任何地方使用,而不必每次想要使用这些方法时都创建一个可空结构实例,例如:
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),因为它是一个实用方法。这是实用方法的预期行为,即使它们可重用于任何需要而不必每次都创建实例。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接