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,
}
Now we can use reflection to rip through ServerEnum and get the conversion mappings from the enum declaration itself.
The problem I am having here is in the declaration of the Enum2Enum attribute.
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){}
}
This fails to compile.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With