简体   繁体   English

泛型:可为空类型的约束

[英]Generics: constraints on nullable types

The following doesn't compile 以下内容无法编译

public static T Retrieve<T>(this NameValueCollection collection, String key) where T : Object
{

    if (collection.AllKeys.Contains(key))
    {
        try
        {
            val = (T)Convert.ChangeType((object)collection[key], typeof(T));
        }
        catch { }
    }

    return val;            
}

because the Constraint cannot be the object class. 因为约束不能是对象类。 So is there a way to contrain T for anything that can be set to a null? 那么有没有一种方法可以将T禁忌为任何可以设置为null的值呢?

where T : class

Your current constraint, where T : Object says "anything which is or inherits from System.Object", which is: everything. 您当前的约束, where T : Object表示“任何来自System.Object或从System.Object继承的东西”,即:一切。 All types, including Int32 and String, inherit from System.Object. 所有类型(包括Int32和String)都从System.Object继承。 So constraining on Object would do nothing. 因此,限制对象将无济于事。

Edit: as usual, Eric shines a light on this in a far more accurate way : 编辑:和往常一样,埃里克(Eric) 以一种更为准确的方式对此进行了说明

"in C# every type derives from object". “在C#中,每种类型都源自对象”。 Not true! 不对! The way to correct this myth is to simply replace "derives from" with "is convertible to", and to ignore pointer types: every non-pointer type in C# is convertible to object. 纠正这个神话的方法是简单地将“源自”转换为“可转换为”,并忽略指针类型: C#中的每个非指针类型都可以转换为对象。

I don't believe it is possible to constrain your generic argument purely to a nullable type. 我认为不可能将您的泛型参数纯粹限制为可为空的类型。 You can easily constrain it to a reference type (as in previous answer), but, while all reference types are nullable, not all nullables are reference types. 您可以轻松地将其约束为引用类型(如上一个答案),但是,尽管所有引用类型都是可为空的,但并非所有可为空的都是引用类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM