设计建议 - 具有属性、接口(或抽象)的类 - 访问问题



我有三个类,即"Class1","Class2"和"Class3"和一个接口IBase。

interface IBase
{
+ PrpCommon {get;set;}
}
Class1:IBase
{
+ PrpCommon {get;set;}
+ Class1Prp {get;set;} ( and few other properties )
}
Class2:IBase
{
+ PrpCommon {get;set;}
+ Class2Prp {get;set;} ( and few other properties )
}
Class3:IBase
{
+ PrpCommon {get;set;}
+ Class3Prp {get;set;} }
AccessClass
{
AccessFunction(IBase)
{
return IBase.PrpCommon;     
// here i need to access the other properties like Class3Prpr or Class2Prp or Class1Prp.
}
}
MainClass
{
AccessClass.AccessFunction(new Class1)  
// Here need to access the other properties like Class3Prpr or Class2Prp or Class1Prp.
}

可能吗???我听说是通过一些构造函数访问它,但不是通过接口......任何想法。


我不确定我是否正确理解了这一点。是否要访问 AccessClass 中派生类的属性? 在这种情况下,一种选择是具有AccessClass的基类或接口,每个IBase类的特定实现以及AccessClassFactory。像这样:

interface IAccessClass
{
AccessFunction<T>(T item) where T : IBase;
}
class AccessClass1 : IAccessClass<Class1>{
AccessFunction(Class1 item){
// here you can do whatever you want with the properties
}
}
class AccessClassFactory{
IAccessClass<T> Create<T>() where T : IBase{
var classType = typeof(T);
if(classType == typeof(Class1)) return new AccessClass1();
// and so on
}
}

我希望你明白了!

最新更新