开发者

Correct way to Inherit multiple interfaces with same methods but different signatures?

开发者 https://www.devze.com 2023-02-07 07:50 出处:网络
After pulling my hair out over this debacle I was hoping an expert could tell me if this is correct. I have these classes:

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>
        wh开发者_如何学Goere TInnerList : ICollection<TObject>, new()

The base class implements void Add for ICollection<T>. 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. 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.

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?


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
}
0

精彩评论

暂无评论...
验证码 换一张
取 消