gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:24:24 27 4
gpt4 key购买 nike

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

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com