简体   繁体   English

如何创建将返回公共接口派生类型的工厂类

[英]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.

相关问题 如何创建返回不同接口类型和抽象类的通用工厂 - How to create a generic factory returning different interface types and an abstract class 您如何制作可以返回派生类型的Factory? - How do you make a Factory that can return derived types? 如何使类工厂创建所需的派生类 - How to make a class factory to create the required derived class 如何在不提及派生类名的情况下返回接口类型? - How to return an interface type without mentioning the derived class name? 如何将新的派生类型添加到工厂模式? - How to add new derived types to a factory pattern? 实现定义基类属性的接口时,为什么类实现接口不能返回派生类类型对象? - When implementing an interface which define a base class property why can't the class implementing interface return a derived class type object? 我将如何配置ninject以将基类工厂用于该类的所有派生类型? - How would I configure ninject to use the base factory for all derived types of that class? 如何在接口派生类型之间转换? - How to Convert between Interface derived types? 返回派生类型的接口 - Interface returning derived types 为实现接口的所有类型注册通用工厂 - Register generic factory for all types which implements an interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM