将接口作为参数而不是特定类型传递

时间:2018-12-06 10:47:10

标签: c# .net

假设我们有这个

    class A { }
    class B : A, IB { }
    interface IB { }
    class C
    {
        private readonly _ib;
        public C(IB ib) {_ib = ib;}
        public void SomeMethod()
        {
            SomeOtherMethod(ib) //which actually requires an object of type A.
        }
    }

SomeOtherMethod需要类型为A的参数,但是我试图用IB来调用它,但是它不起作用,它说:

  

无法从IB转换为A

那是为什么?该如何解决呢?

2 个答案:

答案 0 :(得分:1)

接口不如类具体。您不能通过接口来满足类参数。

如果定义了这样的转换,则可以从接口转换为类,但这是一个狭窄的转换,因此C#不会自动进行转换(除非您将其定义为隐式转换)。

答案 1 :(得分:0)

您可以使用关键字is检查某些类型(例如,针对类的接口)是否兼容,然后使用as将对象转换为所需的类型。

IB不是必需的A,因为IB可以由不继承自A的其他类实现。

class D : IB { } //(d is A) == false

例如,使用您的类结构:

class A { }
class B : A, IB { }
interface IB { }
class C
{
    private readonly IB _ib;
    public C(IB ib) { _ib = ib; }

    public void SomeOtherMethod(A a)
    {
        Debug.WriteLine("I am A");
    }

    public void SomeMethod()
    {
        if (_ib is A)
            SomeOtherMethod(_ib as A); //which actually requires an object of type A.
        else
            Debug.WriteLine("I am not A");
    }
}

class Program
{
    static void Main(string[] args)
    {
        B b = new B();
        C c = new C(b);
        c.SomeMethod();
    }
}

输出

  

我是A

相关问题