在接口签名相同的接口之间进行转换

Dhw*_*hah 4 .net c# casting

当两个接口的签名相同时,是否可以从一个接口转换为另一个接口?以下来源给出Unable to cast object of type 'ConsoleApplication1.First' to type 'ConsoleApplication1.ISecond'.例外情况.

class Program
{
    static void Main(string[] args)
    {
        IFirst x = new First();
        ISecond y = (ISecond)x;
        y.DoSomething();
    }
}

public interface IFirst
{
    string DoSomething();
}

public class First : IFirst
{
    public string DoSomething()
    {
        return "done";
    }
}

public interface ISecond
{
    string DoSomething();
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

当两个接口的签名相同时,是否可以从一个接口转换为另一个接口?

不,就CLR和C#而言,它们是完全不同的类型.

您可以创建一个"桥"类型,它包含委托的实现IFirst和实现ISecond,反之亦然.


pae*_*bal 5

正如Jon Skeet已经回答的那样,不,你做不到.

如果您的问题是编写真正的通用代码,并且如果您不控制接口(如在Baboon提出解决方案中),您仍然可以在C#中执行以下两种方式:

1 - 反思

...使用反射来查询要调用的方法:

object x = new First();

Type t = x.GetType();
MethodInfo mi = t.GetMethod("DoSomething");
mi.Invoke(x, new object[]{}); // will call x.DoSomething
Run Code Online (Sandbox Code Playgroud)

2 - 动态(C#4)

在C#4中,使用dynamic关键字在运行时而不是编译时解析调用:

object x = new First();

dynamic d = x ;   // every call through d will be resolved at runtime
d.DoSomething() ; // compiles (but will throw if there is no 
                  // "DoSomething" method
Run Code Online (Sandbox Code Playgroud)