问题
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
回答1:
public void Foo<T>(T myParam)
where T : IObject, ITreeNode<IObject>
{
// whatever
}
回答2:
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>
.
回答3:
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>
回答4:
public void MethodName<TParam1, TParam2>(TParam1 param1, TParam2 param2)
where TParam1 : IObject
where TParam2 : ITreeNode<IObject>
来源:https://stackoverflow.com/questions/4073440/specifying-multiple-interfaces-for-a-parameter