使用没有在类声明中声明的接口
本文关键字:声明 接口 | 更新日期: 2023-09-27 17:53:48
我实现了两个类:
public class A
{
public string GetName()
{
return "Class A";
}
}
public class B
{
public string GetName()
{
return "Class B";
}
}
我还创建了一个未分配给类A和类B的接口:
public interface TellMyNameInterface
{
string GetName();
}
我想使用类A和类B的接口:
TellMyNameInterface a = new A();
TellMyNameInterface b = new B();
string aName= a.GetName();
是否有任何方法可以使用类A或B的实例与该接口而无需在类声明中声明它?
您不能,但是您可以编写适配器类以使转换更方便,然后使用扩展方法使创建适配器类看起来更自然(并且实际上将适配器类隐藏在接口后面)。
通常只有在无法更改原始类定义以直接实现所需接口时才会这样做。
所以给定这些你不能编辑的类:
public class A
{
public string GetName()
{
return "Class A";
}
}
public class B
{
public string GetName()
{
return "Class B";
}
}
和这个接口,你真的希望他们实现,但不能:
public interface ITellMyNameInterface
{
string GetName();
}
你可以写一对适配器类,让实现接口,像这样:
public class AAdapter: ITellMyNameInterface
{
public AAdapter(A a)
{
_a = a;
}
public string GetName()
{
return _a.GetName();
}
private readonly A _a;
}
public class BAdapter: ITellMyNameInterface
{
public BAdapter(B b)
{
_b = b;
}
public string GetName()
{
return _b.GetName();
}
private readonly B _b;
}
然后编写扩展方法,使创建适配器类更自然:
public static class ABExt
{
public static ITellMyNameInterface AsITellMyNameInterface(this A self)
{
return new AAdapter(self);
}
public static ITellMyNameInterface AsITellMyNameInterface(this B self)
{
return new BAdapter(self);
}
}
一旦您完成了所有这些,它至少使获取A
或B
实例的ITellMyNameInterface
变得更简单,如下所示:
ITellMyNameInterface a = new A().AsITellMyNameInterface();
ITellMyNameInterface b = new B().AsITellMyNameInterface();
不可以。我能看到的唯一方法是使用object
来存储它,然后通过反射调用函数。