gpt4 book ai didi

c# - 嵌套枚举样式和约定

转载 作者:太空宇宙 更新时间:2023-11-03 10:27:51 24 4
gpt4 key购买 nike

我有一个枚举来控制类的运行方式。这个枚举只适用于类,因此感觉应该嵌套。但是,该类需要枚举的一个实例作为成员,理想情况下该实例的名称应与枚举相同。当然,这是不可能的。

我主要关心的是提供干净清晰的 API。我看到的两个选项是:

嵌套枚举并命名实例成员或枚举本身“不够完美”

将枚举放在类之外,这会有点但不会真正污染命名空间,并且可能会降低可发现性。 (现在写这篇文章,让我印象深刻的是,发现能力可能不是问题,因为只有一个使用点,一个属性)。

是否有针对此类情况的公认惯例?这是说明用例的片段:

public class MultiModeActionFacadeObject : IAction
{
public enum ActionMode // enum only applies to this class
{
Fast,
Accurate,
Intermediate
}

private readonly IAction _accurate, _fast, _intermediate;

internal MultiModeActionFacadeObject(IAction fastAction, IAction accurateAction, IAction intermediateAction)
{
_fast = fastAction;
_accurate = accurateAction;
_intermediate = intermediateAction;

}

// preference would be to call this member ActionMode, but obviously members can't share names
// although I believe this could be accomodated, outside of static members, by some changes to
// qualification requirements. That's not the concern here though.
public ActionMode Mode { get; set; }

public void DoWork(object onThis)
{
switch (Mode)
{
case ActionMode.Fast:
_fast.DoWork(onThis);
break;
case ActionMode.Accurate:
_accurate.DoWork(onThis);
break;
case ActionMode.Intermediate:
_intermediate.DoWork(onThis);
break;
}
}
}

最佳答案

将枚举放在类之外似乎更为常见。将其保留在内部意味着您最终需要在每次设置模式时指定 ClassName.Enum:

var mma = new MultiModeActionFacadeObject(fastAction, accurateAction, intermediateAction)
{
Mode =
MultiModeActionFacadeObject.ActionMode.Accurate
};

此外,由于任何一种方式都是有效的,我不认为这是一个明确的“答案”。我只想对您的原始问题添加评论,但这需要 50 多个代表 :)

关于c# - 嵌套枚举样式和约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31147848/

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