问题描述
我想大家都看过code,如:
I imagine everyone has seen code like:
public void Server2ClientEnumConvert( ServerEnum server)
{
switch(server)
{
case ServerEnum.One:
return ClientEnum.ABC
//And so on.
这不是坏,我们可以做财产以后像:
Instead of this badness we could do somthing like:
public enum ServerEnum
{
[Enum2Enum(ClientEnum.ABC)]
One,
}
现在我们可以使用反射从枚举声明本身通过ServerEnum撕裂,并得到转换映射。
Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.
我有这里的问题是在Enum2Enum属性的声明。
The problem I am having here is in the declaration of the Enum2Enum attribute.
这工作,但替换对象o的枚举E不。我不希望能在对象传递给构造函数,只有其他枚举。
This works but replacing object o with Enum e does not. I do not want to be able to pass in objects to the constructor, only other enums.
public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(object o){}
}
这无法编译。
public class EnumToEnumAttribute : Attribute
{
public EnumToEnumAttribute(Enum e){}
}
是否有编译错误的一个原因?我还能怎样传递中,除了地图所需的信息:
Is there a reason for the compile error? How else could I pass in the information needed to map besides:
EnumtoEnumAttribute(Type dest, string enumString)
这似乎过于冗长,但如果它是唯一的出路,然后我想我将使用它。
This seems too verbose but if it is the only way then I guess I will use it.
推荐答案
使用几乎相同的例子,你可以直接在枚举实现这一点:
Using almost the same example, you can achieve this directly in the enum:
public enum ServerEnum
{
One = ClientEnum.ABC,
}
这已经不需要思考的好处,更易于阅读(在我看来),和总体需要更少的开销。
This has the benefit of not requiring Reflection, is easier to read (in my opinion), and overall requires less overhead.
这篇关于使用属性来减少枚举枚举映射和枚举/常量行动开关statments的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!