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
Yes, a class can implement multiple interfaces. Each interface provides contract for some sort of behavior.
A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.
You can implement each individial interface using a separate template and then chain the templates to construct the derived object as if from building blocks. This method was also used by venerable ATL library to implement COM interfaces (for those of us old enough).
No, its an error If two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.
public void Foo<T>(T myParam) where T : IObject, ITreeNode<IObject> { // whatever }
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With