【发布时间】: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