作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
在下面的示例中(仅用于演示目的),如果 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")
做什么?
随着 class
对 CreateObject
的约束,该调用将无效,因为 Foo
不是引用类型——编译器知道 T
是引用类型,所以 objectA as T
没关系。
关于c# - 为什么我不能将 'as' 与被限制为接口(interface)的泛型类型参数一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48109098/
我是一名优秀的程序员,十分优秀!