我在泛型方面遇到了一个奇怪的问题。我收到以下编译错误:
The best overloaded method match has some invalid arguments
Argument '1': cannot convert from 'EntityBase' to 'T'
错误出现在 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 ---
}
}
我有此代码的 VB.NET 版本,可以很好地编译和执行,因此我希望它可以在 C# 中工作。
我在这里缺少什么?
最后,虽然这不重要,但这是 VS2008,.NET 3.5。
最佳答案
让我告诉你为什么你的代码无效:假设我创建了一个 EntityWrapper<MyEntity>
,其中MyEntity
源自BaseEntity
:
var myWrapper = new EntityWrapper<MyEntity>();
EntityWrapper 内部发生了什么?这:
EntityBase.DoSomething<T>(_entity, "some arg");
变成了
EntityBase.DoSomething<MyEntity>(_entity, "some arg");
这是无效的:DoSomething 需要 MyEntity
作为它的第一个参数,但你传递了 BaseEntity
。这就是错误Argument '1': cannot convert from 'EntityBase' to 'T'
意思是。
如何解决这个问题?在 EntityWrapper 中,声明 _entity
如下:
private T _entity;
这允许您保留 _entity
静态键入 BaseEntity
的具体子类型.
关于c# - C# 中的泛型编译错误(但在 VB.NET 中有效),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22866914/