为什么"as T"会出错,但是使用(T)进行转换不会出错?

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)


Yur*_*ich 6

如果T是值类型,这是一个例外,您需要确保T是Nullable或类.