Edw*_*uay 9 c# generics casting
我为什么这样做:
public T GetMainContentItem<T>(string moduleKey, string itemKey)
{
return (T)GetMainContentItem(moduleKey, itemKey);
}
Run Code Online (Sandbox Code Playgroud)
但不是这个:
public T GetMainContentItem<T>(string moduleKey, string itemKey)
{
return GetMainContentItem(moduleKey, itemKey) as T;
}
Run Code Online (Sandbox Code Playgroud)
它抱怨我没有足够的限制泛型类型,但我认为该规则也适用于使用"(T)"进行转换.
n8w*_*wrl 23
因为'T'可以是值类型,'as T'对于值类型没有意义.你可以这样做:
public T GetMainContentItem<T>(string moduleKey, string itemKey)
where T : class
{
return GetMainContentItem(moduleKey, itemKey) as T;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
238 次 |
| 最近记录: |