以下内容无法编译
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;
}
Run Code Online (Sandbox Code Playgroud)
因为Constraint不能是对象类.那么有没有办法将T限制为可以设置为null的任何东西?
Rex*_*x M 13
where T : class
Run Code Online (Sandbox Code Playgroud)
您当前的约束,where T : Object表示"从System.Object继承或继承的任何内容",即:所有内容.所有类型(包括Int32和String)都继承自System.Object.因此限制对象将无能为力.
"在C#中,每种类型都来自于对象".不对!纠正这个神话的方法是简单地将"derives from"替换为"is convertible to",并忽略指针类型:C#中的每个非指针类型都可以转换为object.
| 归档时间: |
|
| 查看次数: |
1431 次 |
| 最近记录: |