繁体   English   中英

如何从实现这两个接口的类访问在两个接口之间定义的参数和方法?

[英]How do I access parameters and methods defined across two interface from a class that implements those two interfaces?

在我的工厂中,我基于一个接口生成对象,但是它实现了两个接口。

例如

myClass1 : Interface1, Interface2 {
   string blah;
   int num;
}

myClass2 : Interface1, Interface2 {
   string blah;
   int num;
}

myClass3 : Interface1, Interface3 {
   string blah;
   bool truefalse;
}

interface Interface1 {
   string blah;
}

interface Interface2 {
   int num;
}

interface Interface3 {
   bool truefalse;
}

但是在我的工厂中,我这样做:

return Activator.CreateInstance(t) as Interface1;

然后我有这个对象

Interface1 inter1;

但是我想做inter1.num但只能访问inter1.blah

好吧,基本上我可以得到实现接口1的所有类型,并获得该功能的新实例是我感兴趣的主要实例。但是之后,我知道那些对象实现了接口2,因此我想访问属性和方法在该接口中定义,而无需重铸到确切的类对象(因为我不知道它到底是哪个)

有没有办法做到这一点?

你并不需要强制转换为具体的类-只投你所感兴趣的接口(或使用as执行条件的演员阵容,并检查其是否成功):

Interface1 x = (Interface1) Activator.CreateInstance(type);
Interface2 y = x as Interface2;
if (y != null)
{
     // Use y
}

当然,如果您可以重构您的接口-或提供扩展两个其他接口的通用接口-更好,但是即使您使用无法更改的接口,上述方法也可以使用。

Interface1Interface2创建一个通用Interface2

interface ICommon : Interface1,Interface2
{  } // you don't need to add anything here

然后为您的类实现此接口,而不是Interface1Interface2 ,并使用

Activator.CreateInstance(t) as ICommon;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM