[英]Generic method type can't be used as generic type for generic class
I want to implement a generic method that should create an instance of a double generic object. 我想实现一个通用方法,该方法应该创建一个双重通用对象的实例。 The generic types of this class that should be instantiated are another class and an interface which the first type must implement.
应该实例化的此类的通用类型是另一个类和第一个类型必须实现的接口。 When I call new in the generic method with its generic type I get the compiler error
CS0311
even if I restrict the type correctly to my base interface. 当我在泛型方法中使用泛型类型调用new时,即使我将类型正确限制在基本接口上,也会出现编译器错误
CS0311
。 Why can't I create an instance like this? 为什么不能创建这样的实例?
class Program
{
static void Main(string[] args)
{
GetQuery<ITESTEntity>();
}
static void GetQuery<I>() where I : IEntityBase
{
var qry = new myQuery<TESTEntity, I>();
}
}
class myQuery<T, I>
where T : class, I
where I : IEntityBase
{
}
Assuming you have these definitions: 假设您具有以下定义:
interface IEntityBase { }
interface ITESTEntity : IEntityBase { }
class TESTEntity : ITESTEntity { }
Then your problem stems from here: 那么您的问题就出在这里:
class myQuery<T, I>
where T : class, I
where I : IEntityBase
You're stating that T
must be assignable to I
, and I
must be assignable to IEntityBase
. 您是在说
T
必须可分配给I
,而且I
必须可分配给IEntityBase
。 That's fine, but here: 很好,但是在这里:
static void GetQuery<I>() where I : IEntityBase
{
var qry = new myQuery<TESTEntity, I>();
You're accepting any I
that's assignable to IEntityBase
. 你接受任何
I
这是分配给IEntityBase
。 So you could also call it like this: 因此,您也可以这样称呼它:
interface ITESTEntity2 : IEntityBase { }
class TESTEntity2 : ITESTEntity2 { }
GetQuery<ITESTEntity2>();
This call would be valid, but now in your method GetQuery()
: 该调用将是有效的,但现在在您的方法
GetQuery()
:
new myQuery<TESTEntity, I>();
I
will be ITESTEntity2
, to which TESTEntity
is not assignable. I
将是ITESTEntity2
,不能将TESTEntity
分配给它。 It can't be guaranteed that TESTEntity
is assignable to any I
where I
is assignable to IEntityBase
, as demonstrated above with ITESTEntity2
. 它不能被保证
TESTEntity
是分配给任何I
其中I
是分配给IEntityBase
,与上述证明ITESTEntity2
。
So reconsider your design. 因此,请重新考虑您的设计。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.