[英]Generics compile error in C# (but works in VB.NET)
I'm having an odd problem with generics. 我在使用泛型时遇到了一个奇怪的问题。 I receive the following compile errors:
我收到以下编译错误:
The best overloaded method match has some invalid arguments
最佳的重载方法匹配具有一些无效的参数
Argument '1': cannot convert from 'EntityBase' to 'T'
参数“ 1”:无法从“ EntityBase”转换为“ T”
The error is in EntityWrapper.DoSomethingElse
, see below: 该错误位于
EntityWrapper.DoSomethingElse
,请参见下文:
public abstract class EntityBase
{
public static bool DoSomething<T>(T entity, string someArg) where T : EntityBase
{
// implementation doesn't matter
return true;
}
}
public class EntityWrapper<T> where T : EntityBase
{
private EntityBase _entity;
public void DoSomethingElse()
{
EntityBase.DoSomething<T>(_entity, "some arg"); // <--- error here ---
}
}
I have a VB.NET version of this code that compiles and executes just fine, so I would expect it to work in C#. 我有此代码的VB.NET版本,可以很好地进行编译和执行,因此我希望它可以在C#中工作。
What am I missing here? 我在这里想念什么?
Finally, though it shouldn't matter, but this is VS2008, .NET 3.5. 最后,尽管没关系,但这是VS2008,.NET 3.5。
Just omit the <T>
. 只需省略
<T>
。 Type inference will figure it out: 类型推断将解决这个问题:
EntityBase.DoSomething(_entity, "some arg");
Let me show you why your code is invalid: Imagine I create an EntityWrapper<MyEntity>
, where MyEntity
derives from BaseEntity
: 让我向您展示为什么您的代码无效:想象一下,我创建了一个
EntityWrapper<MyEntity>
,其中MyEntity
源自BaseEntity
:
var myWrapper = new EntityWrapper<MyEntity>();
What happens inside EntityWrapper? EntityWrapper内部会发生什么? This:
这个:
EntityBase.DoSomething<T>(_entity, "some arg");
becomes 变
EntityBase.DoSomething<MyEntity>(_entity, "some arg");
which is invalid: DoSomething expects a MyEntity
as its first argument, but you pass a BaseEntity
. 这是无效的:DoSomething期望将
MyEntity
作为其第一个参数,但是您传递了BaseEntity
。 This is what the error Argument '1': cannot convert from 'EntityBase' to 'T'
means. 这就是错误
Argument '1': cannot convert from 'EntityBase' to 'T'
意思。
How to fix this? 如何解决这个问题? In EntityWrapper, declare
_entity
as follows: 在EntityWrapper中,声明
_entity
,如下所示:
private T _entity;
This allows you to keep _entity
statically typed to the concrete subtype of BaseEntity
. 这使您可以将
_entity
静态键入为BaseEntity
的具体子类型。
Maybe you could call the method as follows: 也许您可以按以下方式调用该方法:
EntityBase.DoSomething<EntityBase>(_entity, "some arg");
The compiler fails to cast _entity
(which is EntityBase
) to T
(which is specified in the method call). 编译器无法将
_entity
(是EntityBase
) _entity
为T
(在方法调用中指定)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.