c# - 在接口(interface)签名相同的接口(interface)之间转换

标签 c# .net casting

当两个接口(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();
}

最佳答案

Is it possible to cast from one interface to another when both interface's signatures are same?

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

您可以创建一个“桥接”类型,它包装了 IFirst 的实现并通过委托(delegate)实现了 ISecond,反之亦然。

关于c# - 在接口(interface)签名相同的接口(interface)之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9428247/

相关文章:

arrays - 如何在 Scala 中进行装箱?

postgresql - 从 hstore 中删除 key 时出现意外的字符串结尾

c# - 什么支持Excel更好? (VB.net 或 C#.net ??)

c# - 类型 'Microsoft.SqlServer.Types.SqlGeography' 存在于 'Microsoft.SqlServer.Types.dll' 和 'Microsoft.SqlServer.Types.dll' 中

c# - NHibernate 拦截器不工作

.net - 如何从自定义编辑器更新 PropertyGrid?

apache-spark - 如何在 Spark SQL 中捕获转换问题

c# - UWP Windows 10 未触发 OnSuspending 事件

c# - 访问嵌套类

c# - 为什么 Math.Round/Floor/Ceiling 不返回 long 或 int?