当两个接口(interface)的签名相同时,是否可以从一个接口(interface)转换到另一个接口(interface)?以下来源给出了 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();
}
最佳答案
不。就 CLR 和 C# 而言,它们是完全不同的类型。
您可以创建一个“桥接”类型,它包装 IFirst
的实现并通过委托(delegate)实现 ISecond
,反之亦然。
关于c# - 在接口(interface)签名相同的接口(interface)之间进行转换,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9428247/