为一个参数指定多个接口
我有一个实现两个接口的对象...接口是:
public interface IObject
{
string Name { get; }
string Class { get; }
IEnumerable<IObjectProperty> Properties { get; }
}
public interface ITreeNode<T>
{
T Parent { get; }
IEnumerable<T> Children { get; }
}
这样
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; }
}
现在我有一个函数需要其参数之一来实现这两个接口。我将如何在 C# 中指定它?
一个例子是
public TypedObject(ITreeNode<IObject> baseObject, IEnumerable<IType> types, ITreeNode<IObject>, IObject parent)
{
//Construct here
}
或者问题是我的设计是错误的,我应该以某种方式在一个接口上实现这两个接口
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 C# 中,接口本身可以从一个或多个其他接口继承。因此,一种解决方案是定义一个接口,例如从
IObject
和ITreeNode
派生的IObjectTreeNode
。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 bothIObject
andITreeNode<T>
.定义一个同时实现 IObject 和 ITreeNode 的接口可能是最简单的。
如果您不希望经常使用上述接口,另一种选择是使有问题的方法/函数通用。
It's probably easiest to define an interface that implements both IObject and ITreeNode.
Another option, in case you don't expect the above interface would be used often, is to make the method/function in question generic.