得到一个类没有很多的if语句 [英] get a class without a lot of if statements

查看:122
本文介绍了得到一个类没有很多的if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一定量的类从一个抽象类继承:

I have a certain amount of classes which inherit from an abstract class:

abstract public class baseClass
{
    //logics
}

public class child1 : baseClass
{
}

public class child2 : baseClass
{
}

现在我有一些将要创建管理类取决于枚举这些类,这将具有与价值相同的名称之一,所以这样的:

now I've got some management class which will have to create one of these classes depending on a enum which will have as value the same name so like this:

public enum ClassType
{
    child1,
    child2
}

public class Manager
{
    private List<baseClass> _workers;

    public void Initialize(ClassType type)
    {
        //what logics to put here? (resulting in correctChild)
        _workers.Add(correctChild);
    }
}



我想typeof运算,但不太知道如何实现它。
注:在本例中是2类,但在现实情况下,它的类任意金额

I was thinking of typeof but don't know quite how to implement it. Note: in this example it's 2 classes but in the real case it's an arbitrary amount of classes.

推荐答案

如果。你不需要的属性的开销,你是从同一程序集运行这一点 - 你可以只使用执行大会通过反射加载类型。 Activator.CreateInstance 可以照顾动态生成的对象为你的。

If you don't need the overhead of attributes and you are running this from the same assembly - you can just use the executing assembly to load the type via reflection. Activator.CreateInstance can take care of building the object for you dynamically.

public class Manager
{
    private List<baseClass> _workers = new List<baseClass>();

    public void Initialize(ClassType type)
    {
        string assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
        Type objType = Type.GetType(string.Format("{0}.{1},{0}", assemblyName, type.ToString()));
        var correctChild =  (baseClass)Activator.CreateInstance(objType);
        _workers.Add(correctChild);
    }
}

这篇关于得到一个类没有很多的if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆