[英]How to create factory class which will return the derived types of common interface
I have an Interface and it is implemented by many classes.我有一个接口,它由许多类实现。 Each class also has its own set of properties which are not present in interface.
每个类还有自己的一组属性,这些属性在接口中不存在。 Now, if I want to design a factory which returns of type interface, I cannot set some of the derived class properties as they are not member of interface.
现在,如果我想设计一个返回接口类型的工厂,我不能设置一些派生类属性,因为它们不是接口的成员。
How to address this scenario?如何应对这种情况?
If you have an Interface like如果你有一个像
public interface MyInterface
{
string Name { get; }
}
and implementations like和实现如
public class MyClass : MyInterface
{
string Name { get; set; }
int Something { get; set; }
}
public class MySecondClass : MyInterface
{
string Name { get; set; }
decimal SomethingElse { get; set; }
}
you can create your class in the factory like你可以在工厂中创建你的类
public class MyFactory
{
public MyInterface createMyClass()
{
return new MyClass() { Name = "foo", Something = 42 };
}
public MyInterface createMySecondClass()
{
return new MySecondClass() { Name = "bar", SomethingElse = 4.2M };
}
}
Of course this way you can't access the members you don't have declared in your interface.当然,这样你就不能访问你没有在接口中声明的成员。
var something = myFactory.createMyClass().Something;
This wouldn't work.这行不通。 You can only access the name property:
您只能访问 name 属性:
var name = myFactory.createMyClass().Name;
If you would want to access the special property of your class, you would have to cast your interface to the actual class:如果您想访问类的特殊属性,则必须将接口强制转换为实际类:
var something = ((MyClass)myFactory.createMyClass()).Something;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.