gpt4 book ai didi

c# - 为什么我不能将 'as' 与被限制为接口(interface)的泛型类型参数一起使用?

转载 作者:IT王子 更新时间:2023-10-29 04:30:19 26 4
gpt4 key购买 nike

在下面的示例中(仅用于演示目的),如果 T 不受类约束,则此转换:

var ret = objectA as T;

..将导致以下编译错误:

The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint.

我不明白为什么我不能这样做。由于我已将 T 约束为接口(interface) IObject,因此编译器应该知道 T 必须是接口(interface)类型并且 as 操作应该是有效的。

public interface IObject
{
string Id { get; set; }
}
public class ObjectA : IObject
{
public string Id { get; set; }
}
public class ObjectFactory
{
public T CreateObject<T>(string id) where T : IObject
{
ObjectA objectA = new ObjectA();
var x = objectA as IObject; // this is good
var ret = objectA as T; // why this 'as' cannot compile?
return ret;
}
public T CreateClassObject<T>(string id) where T : class, IObject
{
ObjectA objectA = new ObjectA();
var ret = objectA as T; // if T is class, this 'as' can compile
return ret;
}
}

最佳答案

since I have constrained T to be interface IObject, compiler should know that T must be an interface type and the 'as' operation should be valid.

不,T不必是接口(interface)类型。它必须是实现接口(interface)的类型。考虑:

public struct Foo : IObject
{
public string Id { get; set; }
}

现在你会期待什么CreateObject<Foo>("ff")做什么?

随着 classCreateObject 的约束,该调用将无效,因为 Foo不是引用类型——编译器知道 T是引用类型,所以 objectA as T没关系。

关于c# - 为什么我不能将 'as' 与被限制为接口(interface)的泛型类型参数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48109098/

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