所以我有两个接口:
public interface ISomething
{
public int A();
}
public interface ISomethingElse
{
public int B();
}
Run Code Online (Sandbox Code Playgroud)
并且实现两者的对象:
public class MyObject : ISomething, ISomethingElse
{
}
Run Code Online (Sandbox Code Playgroud)
现在我有这个运行代码:
...
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
...
Run Code Online (Sandbox Code Playgroud)
如果我想在所有这些上调用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();
}
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能干净地打电话MyUtilityClass.MySpecialMethod()给我List<MyObject> objects?没有所有类型转换是否可能?参数MyUtilityClass.MySpecialMethod()似乎是问题(我想将参数定义为实现ISomething的对象列表).
| 归档时间: |
|
| 查看次数: |
439 次 |
| 最近记录: |