gpt4 book ai didi

c# - 枚举可以在 C# 中返回一个新实例吗?

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

大家好!

我会尽量简化我的问题:我有一个 enum 来选择我应该使用哪个 ObjType(ObjTypeAObjTypeB 都继承自 ObjType)。所以我创建了一个方法来扩展给定的 enum,以便根据 enum 中的选定属性返回一个新实例,如下代码所示。我认为它的工作方式或多或少类似于工厂设计模式。到目前为止一切顺利,但最终,就像在类 MyClass 中一样,我可能会尝试创建 n ObjTypeAObjTypeB< 的实例,但每次调用 GetObjTypeInstance() 方法时,我都必须面对 if 语句。所以:

  • enum 能否返回一个实例,例如:public enum EObjType { ObjTypeA = new ObjTypeA(), ObjTypeB = new ObjTypeB() }?实际上,最好将一些 GetInstance() 方法附加到 ObjTypeAenum< 中的 ObjTypeB 选项。如果有办法做到这一点,我该怎么做?这样做我会在每个 while 步骤中避免那些 if 语句。
  • 有没有其他(更好)的方法来解决这个问题(如果您理解我的问题...)?怎么样?

提前致谢!

按照示例代码:

public static class EObjTypeExt
{
public static ObjType GetObjTypeInstance(this EObjType ot)
{
if (ot == EObjType.ObjTypeA)
{
return new ObjTypeA();
}
else if (ot == EObjType.ObjTypeB)
{
return new ObjTypeB();
}
throw new ArgumentOutOfRangeException("unrecognized type!");
}
}

public enum EObjType { ObjTypeA, ObjTypeB }

public class MyClass
{
ObjType[] obj { get; set; }

public MyClass(EObjType otEnum, int n)
{
this.obj = new ObjType[n];
int i = 0;
while (i < n)
{
this.obj[i] = otEnum.GetObjTypeInstance();
i++;
}
}
}

最佳答案

你必须把这个苹果咬在某个地方。

也许用 switch 语句替换 if/elseif 链,它们与枚举一起工作得很好。

关于c# - 枚举可以在 C# 中返回一个新实例吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6037771/

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