gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:29:59 26 4
gpt4 key购买 nike

为什么我可以这样做:

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

最佳答案

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

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

关于c# - 为什么 "as T"会出错,但使用 (T) 进行转换不会出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1178280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com