C#,对象和多个接口实现:如何正确使用?

Cym*_*men 2 c# interface

所以我有两个接口:

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的对象列表).

oxi*_*min 5

您可以使用IEnumerable<>界面而不是List<>.IEnumerable<>是协变的.