9

为什么我可以这样做:

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)”进行强制转换。

4

5 回答 5

23

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

public T GetMainContentItem<T>(string moduleKey, string itemKey)
    where T : class
{
    return GetMainContentItem(moduleKey, itemKey) as T;
}
于 2009-07-24T15:06:21.580 回答
6

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

于 2009-07-24T15:06:11.440 回答
1

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

于 2009-07-24T15:07:30.610 回答
0

延伸 Yuriy Faktorovichs 的回答:

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

这会成功的......

于 2009-07-24T15:07:58.660 回答
0

因为as T检索null以防它无法强制转换T,而不是(T)引发异常。所以如果T不是Nullableclass不可能null......我想。

于 2009-07-24T15:09:58.673 回答