Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将对象强制转换为非显式实现的接口_C#_Inheritance - Fatal编程技术网

C# 将对象强制转换为非显式实现的接口

C# 将对象强制转换为非显式实现的接口,c#,inheritance,C#,Inheritance,是否有可能将对象强制转换到它不直接继承的接口?在下面的示例代码中,是否有任何方法可以将All实例转换为单个实例 public interface IA { void A(); } public interface IB { void B(); } public interface IC : IA, IB { } public class All : IA, IB { public void A() { Console.Out.WriteLi

是否有可能将对象强制转换到它不直接继承的接口?在下面的示例代码中,是否有任何方法可以将All实例转换为单个实例

public interface  IA
{
    void A();
}

public interface IB
{
    void B();
}

public interface IC : IA, IB
{
}

public class All : IA, IB
{
    public void A()
    {
        Console.Out.WriteLine("ALL A");
    }

    public void B()
    {
        Console.Out.WriteLine("ALL B");
    }
}

public class Single : IC
{
    public void A()
    {
        Console.Out.WriteLine("SINGLE A");
    }

    public void B()
    {
        Console.Out.WriteLine("SINGLE B");
    }
}

class Program
{
    static void Main()
    {
        All all = new All();
        Single single = (Single)(all as IC); // Always null
        single?.A();
    }
}
您将需要使用


请注意,与
接口
不同,您不能强制将一个具体类型转换为另一个具体类型(在本例中,您的强制转换为
Single
),必须将局部变量类型从具体类型(
Single
)更改为接口(
IC
)。

All
实际上根本没有实现
IC
(“间接继承”是另一回事)。听起来你在追求duck类型,而C#不支持(
dynamic
不算在内)@Dai不,没有明确说明,但事实上它们共享相同的签名。只是想知道这是否可以实现,但猜测不可能;-)关键是在
IC
中,您可以实现/添加许多新功能。将
all
转换为
IC之后,在这些场景中
single
的行为会是什么类型。因此它不受支持。谢谢。对于
AllIC
实例,这是一个可能的解决方案,您不需要
作为IC
。并且您将在转换为
时获得运行时异常(单条)
因为
AllIC
不是一个
单曲
@SergeyBerezovskiy,我忽略了
单曲
类。我已经更正了我的答案。
class AllIC : IC {
    private readonly All all;
    public AllIC(All all) {
        if( all == null ) throw new ArgumentNullException(nameof(all));
        this.all = all;
    }

    public void A() => this.all.A();
    public void B() => this.all.B();
}

static void Main()
{
    All all = new All();
    IC ic = new AllIC( all ); // Observe that `ic` is typed as interface `IC` instead of the concrete type `Single`.
    ic.A();
}