【问题标题】:Generic method working for one class but not the other, with the same interface通用方法适用于一个类但不适用于另一个类,具有相同的接口
【发布时间】:2017-12-14 22:02:52
【问题描述】:

我有两门课

[DataContract]
public class HiveReference : IGUID
{
    [BsonId]
    [DataMember]
    public Guid GUID{ get; set; }
    ....
}
...

[DataContract]
public class HiveByteChunk : IGUID
{
    [DataMember]
    [BsonId]
    public Guid GUID { get; set; }
    ...
}

我的界面...

public interface IGUID
{
    Guid GUID {get;set;}
}

那我有一个扩展方法……

public static void InsertIfNotExists<T>(this T member) where T: IGUID
{
    if (!(member).Exists())
    {
        member.Insert();
    }
}

public static void Insert(this object member) 
{
    DBHelper.Insert(member);
}

那我的实现代码……

HiveReference hf = new HiveReference();
hf.InsertIfNotExists();

HiveByteChunk chunk = new HiveByteChunk();
chunk.InsertIfNotExists();

最后一个换行符,编译器错误:

Error   CS0311
    The type 'HiveLibrary.HiveBytes.HiveByteChunk' cannot be used as type parameter 'T' in the generic type or method 'Extensions.InsertIfNotExists<T>(T)'.
    There is no implicit reference conversion from 'HiveLibrary.HiveBytes.HiveByteChunk' to 'HiveLibrary.IGUID'.

如果两个类都实现了接口,为什么第一个类可以调用扩展,而最后一个不能?我错过了什么明显的东西吗?

【问题讨论】:

  • 嗯,实际上这是不可能的。你肯定错过了你的帖子中也缺少的东西。你能尝试生成一个minimal reproducible example(发布最小但完整的代码来重现问题)。
  • 两个类都实现HiveLibrary.IGUID吗?
  • 奇怪的是 [DataMember] [BsonId] 的顺序会有所不同...您在两者上方都有 [DataContract] 吗? (你有......在另一个之上,不能说)
  • @KevinCook - 属性的顺序无关紧要 - 参见 this,例如。
  • 会不会有另一个 IGUID 在不同的命名空间中,而 HiveByteChunk 实现了它?

标签: c# interface generic-method


【解决方案1】:

问题是我在不同的命名空间中有一个重复的接口。一旦我删除它,一切都按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 2021-07-18
    相关资源
    最近更新 更多