c# - C# 中的泛型编译错误(但在 VB.NET 中有效)

标签 c# .net vb.net generics compiler-errors

我在泛型方面遇到了一个奇怪的问题。我收到以下编译错误:

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/

相关文章:

c# - 测试工具与测试框架有何不同/

c# - 集合<T> : why does it implement both IEnumerable and IEnumerable<T>?

c# - 如何在 .NET 2.0 中获取 Environment.SpecialFolders.MyVideo 文件夹?

c# - 如何检查泛型类型定义是否继承自另一个泛型类型定义

arrays - 如何在不使用 LINQ 的情况下按降序对 FileInfo 对象数组进行排序

vb.net - 包含表单的 .NET 类库中的 SetCompatibleTextRenderingDefault

c# - 用于 C# 对象数据源的 EDI x12 映射器

.net - System.Windows.Forms.Keys枚举中的 “OEM”键是什么?

c# - 如何让枚举值带有空格?

c# - VB.NET 问题。林克支持?