C#、对象和多个接口实现:如何正确使用?
所以我有两个接口:
public interface ISomething
{
public int A();
}
public interface ISomethingElse
{
public int B();
}
以及一个实现这两个接口的对象:
public class MyObject : ISomething, ISomethingElse
{
}
现在我有这个正在运行的代码:
...
List<MyObject> objects = myObjectManager.SelectAll(); // now have say 10 MyObject
MyUtilityClass myUtilityClass = new MyUtilityClass();
MyOtherUtilityClass myOtherUtilityClass = new MyOtherUtilityClass();
myUtilityClass.MySpecialMethod(objects); // <- compile failure
myOtherUtilityClass.MySpecialMethod(objects); // <- another failure
...
如果我想在所有接口上调用 A 或 B,我该如何编写这样的代码:
public class MyUtilityClass
{
public void MySpecialMethod(List<ISomething> objects) // <- the problem
{
foreach (ISomething o in objects)
o.A();
}
}
public class MyOtherUtilityClass
{
public void MySpecialMethod(List<ISomethingElse> objects) // <- the problem
{
foreach (ISomethingElse o in objects)
o.B();
}
}
如何干净地调用 MyUtilityClass我的
?是否可以不进行所有类型转换? List
对象MyUtilityClass.MySpecialMethod()
的参数似乎是问题所在(我想将参数定义为实现 ISomething 的对象列表)。
So I have two interfaces:
public interface ISomething
{
public int A();
}
public interface ISomethingElse
{
public int B();
}
And an object that implements both:
public class MyObject : ISomething, ISomethingElse
{
}
Now I have this running code:
...
List<MyObject> objects = myObjectManager.SelectAll(); // now have say 10 MyObject
MyUtilityClass myUtilityClass = new MyUtilityClass();
MyOtherUtilityClass myOtherUtilityClass = new MyOtherUtilityClass();
myUtilityClass.MySpecialMethod(objects); // <- compile failure
myOtherUtilityClass.MySpecialMethod(objects); // <- another failure
...
If I want to call A or B on all of them, how can I write code like this:
public class MyUtilityClass
{
public void MySpecialMethod(List<ISomething> objects) // <- the problem
{
foreach (ISomething o in objects)
o.A();
}
}
public class MyOtherUtilityClass
{
public void MySpecialMethod(List<ISomethingElse> objects) // <- the problem
{
foreach (ISomethingElse o in objects)
o.B();
}
}
How can I cleanly call MyUtilityClass.MySpecialMethod()
on my List<MyObject> objects
? Is it possible without all typecasting? The parameters of MyUtilityClass.MySpecialMethod()
appear to be the issue (I want to define the parameter as a List of objects that implement ISomething).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
IEnumerable
接口代替List
。IEnumerable<>
是协变的。You can use
IEnumerable<>
interface instead ofList<>
.IEnumerable<>
is covariant.列表不支持协方差。
您可以将其更改为
IEnumerable
并传递List
。List does not support covariance.
You may change it to
IEnumerable<ISomething>
and pass aList<MyObject>
.就个人而言,我会使用以下签名,因为
IEnumerable
是协变的:调用它:
Personally, I would use the following signature as
IEnumerable<T>
is covariant:Calling it:
不应该
工作吗?
Shouldn't
work?