Generics: constraints on nullable types
The following doesn't compile
开发者_JAVA技巧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?
where T : class
Your current constraint, where T : Object
says "anything which is or inherits from System.Object", which is: everything. All types, including Int32 and String, inherit from System.Object. So constraining on Object would do nothing.
Edit: as usual, Eric shines a light on this in a far more accurate way:
"in C# every type derives from object". 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.
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.
精彩评论