将对象转换为非显式实现的接口

时间:2017-07-07 21:44:23

标签: c# inheritance

以某种方式可以将对象强制转换为不直接继承的接口?在下面的示例代码中,有没有办法将All实例转换为Single实例?

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();
    }
}

1 个答案:

答案 0 :(得分:3)

您需要使用the Adapter Pattern

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();
}

请注意,与interfaces不同,您不能将一种具体类型强制转换为另一种(在这种情况下,您的转换为Single),您必须从具体类型({{1})更改本地变量类型})到接口(Single)。