c# - 创建未知类型的实例

标签 c# reflection

我很确定有几种不同的方法可以做到这一点,因为我已经非常接近它但没有成功,但我想看看你对我的具体案例的看法.

有没有办法避免这种切换?

Resource r = null; < --Resource is the base class of block,rock,plant types.

switch (type) //type is a byte you get from somewhere on runtime
{
        //Then you instantiate that class type depending on that "type byte",
        //simply by comparing it to an enum lets say

    case ResourceType.Block:
        r = new Block();
        break;
    case ResourceType.Rock:
        r = new Rock();
        break;
    case ResourceType.Plant:
        r = new Plant();
        break;
 }

//Then you apply some data to that newly created 'resource"
r.id = id;

//Then you save that 'resource' into a dictionary of resources.
ResourceDatabase.Add(r.id, r);

最佳答案

我的方法是使用字典来构建映射。字典可以在运行时修改,并且可以在需要时使用反射动态填充。

var factory = new Dictionary<ResourceType, Func<Resource>>()
{
    { ResourceType.Block, () => new Block() },
    { ResourceType.Rock, () => new Rock() },
    { ResourceType.Plant, () => new Plant() },
};

Resource r = factory[type].Invoke();

关于c# - 创建未知类型的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37504751/

相关文章:

c# - 在 .net 中隐藏私有(private)字段以防止反射

c# - 在 C# 中将 DataTable 转换为 List<T>

c# - 好的 lambda 表达式或减少每个循环的更好方法

c# - Blazor 编译器如何生成序列号?

Android,如何清除大多数手机中可以从主页按钮获得的最近任务列表?反射(reflection)是一种可能的方式吗?

java - "Object Breakpoint"- 如何在具有复杂动态行为的大型代码库中调试对特定对象的访问?

c# - 如何在 Type.GetMethods 中排除 "property methods"?

c# - 如何在网络方法中访问 session ?

c# - 由于 'System.DateTime' 准确度,成组运行时单元测试运行速度过快

c# - MVC RadioButtonFor 组