使用属性减少枚举到枚举的映射以及枚举/常量到动作切换的语句

时间:2020-03-05 18:46:36  来源:igfitidea点击:

我想每个人都看过这样的代码:

public void Server2ClientEnumConvert( ServerEnum server)
{
    switch(server)
    {
       case ServerEnum.One:
           return ClientEnum.ABC
       //And so on.

除了这种弊端,我们还可以做类似的事情:

public enum ServerEnum
{
     [Enum2Enum(ClientEnum.ABC)]
     One,
}

现在,我们可以使用反射来遍历ServerEnum并从枚举声明本身获取转换映射。

我在这里遇到的问题是在Enum2Enum属性的声明中。

这可行,但是用枚举e替换对象o无效。我不希望仅将其他枚举传递给构造函数。

public class EnumToEnumAttribute : Attribute
{
    public EnumToEnumAttribute(object o){}
}

这无法编译。

public class EnumToEnumAttribute : Attribute
{
    public EnumToEnumAttribute(Enum e){}
}

有编译错误的原因吗?除了:

EnumtoEnumAttribute(Type dest, string enumString)

这似乎太冗长,但是如果这是唯一的方法,那么我想我会用它。

解决方案

回答

我可能会使用struct作为类型,如果不是Enum类型,则抛出异常。我看不出(类型,字符串)选项比使用对象或者结构更安全。

回答

以下是可以作为属性参数包含的类型的规则:

回答

@Danial Jennings I read through the rules there and found: "An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility (Section 17.2).".

如何根据引用规则在构造函数中尝试Enum e失败?是否因为枚举类型不能保证传入的枚举是公开可见的?这似乎是对的。有没有办法在编译时强制执行此规则?

@ bdukes You are exactly correct. I should have thought about that more.

看起来运行时类型检查是确保我仅将枚举映射到其他枚举的唯一选择。

回答

为什么不使用字典?这可能是类的静态属性,并使用我们在3.0中获得的那些花哨的schmancy对象初始化程序进行了初始化?我们无需输入更多代码(即使使用属性解决方案也必须完成映射)。

回答

使用几乎相同的示例,我们可以直接在枚举中实现此目的:

public enum ServerEnum
{
   One = ClientEnum.ABC,
}

这样的好处是不需要反射,更容易阅读(我认为),并且总体上需要更少的开销。