[英]Correct way to Inherit multiple interfaces with same methods but different signatures?
After pulling my hair out over this debacle I was hoping an expert could tell me if this is correct. 在经历这场灾难之后拔掉头发后,我希望专家可以告诉我这是否正确。
I have these classes: 我有这些课:
public class ParentAwareHashset<TObject, TParent> :
ParentAwareCollection<TObject,TParent, HashSet<TObject>>,
ICollection<TObject>, ISet<TObject>
where TObject : IParentProvider<TParent>
public abstract class ParentAwareCollection<TObject, TParent, TInnerList> :
ICollection<TObject>, IParentProvider<TParent>
where TObject : IParentProvider<TParent>
where TInnerList : ICollection<TObject>, new()
The base class implements void Add
for ICollection<T>
. 基类实现
ICollection<T>
void Add
。 In my inherited class, I got into trouble by implementing public new bool Add(TObject item)
which is the only way to implement the bool Add
ISet method, since the signature doesn't match the underlying void Add
method. 在继承的类中,我遇到了麻烦,因为实现了
public new bool Add(TObject item)
,这是实现bool Add
ISet方法的唯一方法,因为签名与底层的void Add
方法不匹配。 So what happend was, I happened to do something to it with a method that only had an implementation for ICollection
, the base class Add
method was being used. 所以发生了什么事,我碰巧用一个仅对
ICollection
实现的方法对它做了什么,正在使用基类Add
方法。
I think I figured out how to do this right... but I am still not sure I will avoid any unexpected behavior, so was hoping some guru could confirm or deny this approach. 我想我想出了正确的方法...但是我仍然不确定我是否会避免任何意外的行为,因此希望一些专家可以确认或拒绝这种方法。
bool ISet<TObject>.Add(TObject item)
{
return(Add(item));
}
void ICollection<TObject>.Add(TObject item)
{
throw new Exception(@"You probably didn't mean for this to happen, you're
using a method that doesn't have an ISet implementation.");
}
public new virtual bool Add(TObject item)
{
// my actual add code
}
Can someone tell me if an object of type ParentAwareHashset would be guaranteed to always run the "new" method, or fail? 有人可以告诉我是否可以保证类型为ParentAwareHashset的对象始终运行“新”方法,否则失败?
Just have the explicitly implemented interface methods call the correct method rather than throwing an exception: 只是让显式实现的接口方法调用正确的方法,而不是引发异常:
bool ISet<TObject>.Add(TObject item)
{
return(Add(item));
}
void ICollection<TObject>.Add(TObject item)
{
**return(Add(item))**;
}
public new virtual bool Add(TObject item)
{
// my actual add code
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.