在接口签名相同的接口之间转换 [英] Cast between interfaces whose interface signatures are same

查看:126
本文介绍了在接口签名相同的接口之间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从一个接口转换为另一种当两个接口的签名是一样的吗?下面的源给人无法转换类型'ConsoleApplication1.First对象键入'ConsoleApplication1.ISecond。例外。

 类节目
{
静态无效的主要(字串[] args)
{
IFirst X =新的第一() ;
ISecond Y =(ISecond)×;
y.DoSomething();
}
}

公共接口IFirst
{
串DoSomething的();
}

公共类第一:IFirst
{
公共字符串DoSomething的()
{
返回完成;
}
}

公共接口ISecond
{
串DoSomething的();
}


解决方案

是否有可能从投下接口之间当两个接口的签名是一样的吗?




没有。他们尽可能的CLR和C#都在关注完全不同的类型。



您可以创建一个桥梁类型,包装的实施IFirst 和农具 ISecond 由代表团,反之亦然。


Is it possible to cast from one interface to another when both interface's signatures are same? The below source is giving the Unable to cast object of type 'ConsoleApplication1.First' to type 'ConsoleApplication1.ISecond'. exception.

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?

No. They're completely different types as far as the CLR and C# are concerned.

You could create a "bridge" type which wraps an implementation of IFirst and implements ISecond by delegation, or vice versa.

这篇关于在接口签名相同的接口之间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆