Specifying multiple interfaces for a parameter

2020-05-22 00:28发布

I have an object that implements two interfaces... The interfaces are:

public interface IObject
{
    string Name { get; }
    string Class { get; }
    IEnumerable<IObjectProperty> Properties { get; }
}
public interface ITreeNode<T>
{
    T Parent { get; }
    IEnumerable<T> Children { get; }
}

such that

public class ObjectNode : IObject, ITreeNode<IObject>
{
    public string Class { get; private set; }
    public string Name { get; private set; }
    public IEnumerable<IObjectProperty> Properties { get; set; }
    public IEnumerable<IObject> Children { get; private set; }
    public IObject Parent { get; private set; }
}

Now i have a function which needs one of its parameters to implement both of these interfaces. How would i go about specifying that in C#?

An example would be

public TypedObject(ITreeNode<IObject> baseObject, IEnumerable<IType> types, ITreeNode<IObject>, IObject parent)
{
    //Construct here
}

Or is the problem that my design is wrong and i should be implementing both those interfaces on one interface somehow

4条回答
forever°为你锁心
2楼-- · 2020-05-22 00:41

It's probably easiest to define an interface that implements both IObject and ITreeNode.

public interface IObjectNode<T> : IObject, ITreeNode<T>
{
}

Another option, in case you don't expect the above interface would be used often, is to make the method/function in question generic.

public void Foo<T>(T objectNode) where T : IObject, ITreeNode<IObject>
查看更多
狗以群分
3楼-- · 2020-05-22 00:41
public  void MethodName<TParam1, TParam2>(TParam1 param1, TParam2 param2) 
    where TParam1 : IObject
    where TParam2 : ITreeNode<IObject> 
查看更多
来,给爷笑一个
4楼-- · 2020-05-22 00:47
public void Foo<T>(T myParam)
    where T : IObject, ITreeNode<IObject>
{
    // whatever
}
查看更多
Bombasti
5楼-- · 2020-05-22 00:51

In C#, interfaces can themselves inherit from one or more other interfaces. So one solution would be to define an interface, say IObjectTreeNode<T> that derives from both IObject and ITreeNode<T>.

查看更多
登录 后发表回答