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

时间:2009-07-24 15:04:05

标签: c# generics casting

为什么我可以这样做:

public T GetMainContentItem<T>(string moduleKey, string itemKey)
{
    return (T)GetMainContentItem(moduleKey, itemKey);
}

但不是这样:

public T GetMainContentItem<T>(string moduleKey, string itemKey)
{
    return GetMainContentItem(moduleKey, itemKey) as T;
}

它抱怨我没有足够的限制泛型类型,但我认为该规则也适用于使用“(T)”进行投射。

5 个答案:

答案 0 :(得分:23)

因为'T'可以是值类型,'因为T'对于值类型没有意义。你可以这样做:

public T GetMainContentItem<T>(string moduleKey, string itemKey)
    where T : class
{
    return GetMainContentItem(moduleKey, itemKey) as T;
}

答案 1 :(得分:6)

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

答案 2 :(得分:1)

T是值类型吗?如果是这样,如果as运算符失败,它将返回null,它不能存储在值类型中。

答案 3 :(得分:0)

延伸Yuriy Faktorovichs回答:

public T GetMainContentItem<T>(string moduleKey, string itemKey) where T: class
{
    return GetMainContentItem(moduleKey, itemKey) as T;
}

这样可以解决问题......

答案 4 :(得分:0)

因为as T无法转发null而不是T引发异常,所以(T)会检索T。因此,如果Nullable不是classnull,则不能{{1}} ......我认为。