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

Why can't I use 'as' with generic type parameter that is constrained to be an interface?

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

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 约束为接口 IObject,因此编译器应该知道 T 必须是接口类型并且 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 不必是接口类型。它必须是 实现接口 的类型。考虑:

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

现在您希望 CreateObject<Foo>("ff") 做什么?

使用 CreateObject 上的 class 约束,该调用将无效,因为 Foo 不是引用类型 - 编译器知道 T 是引用类型,所以 objectA as T 没问题。