我实施了2个课程:
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类实例?
答案 0 :(得分:1)
您不能,但您可以编写适配器类以使转换更方便,然后使用扩展方法使创建适配器类看起来更自然(实际上隐藏了接口后面的适配器类)。 / p>
如果您无法更改原始类定义以直接实现所需的接口,通常只会执行此操作。
因此,鉴于您无法编辑这些类:
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);
}
}
完成所有这些操作后,至少可以更轻松地获取ITellMyNameInterface
或A
实例的B
,如下所示:
ITellMyNameInterface a = new A().AsITellMyNameInterface();
ITellMyNameInterface b = new B().AsITellMyNameInterface();
答案 1 :(得分:0)
不,你不能。我能看到的唯一方法是使用object
来存储它,然后通过反射调用函数。