使用用户定义的转换将字符串转换为类型安全枚举 [英] Casting string to type-safe-enum using user-defined conversion
问题描述
为了使用枚举与字符串相结合,我实现了一个基于 http://stackoverflow.com/a/的StringEnum类424414/1293385 。
In order to use Enum's in combination with strings, I implemented a StringEnum class based on http://stackoverflow.com/a/424414/1293385.
但是,当我尝试实现建议的用户定义的转换操作时遇到问题。
However I run into problems when I try to implement the suggested user-defined conversion operations.
StringEnum类定义如下:
The StringEnum class is defined as follows:
public abstract class StringEnum
{
private readonly String name;
private readonly int value;
protected static Dictionary<string, StringEnum> instances
= new Dictionary<string, StringEnum>();
protected StringEnum(int value, string name)
{
this.value = value;
this.name = name;
instances.Add(name.ToLower(), this);
}
public static explicit operator StringEnum(string name)
{
StringEnum se;
if (instances.TryGetValue(name.ToLower(), out se))
{
return se;
}
throw new InvalidCastException();
}
public override string ToString()
{
return name;
}
}
我使用这个类作为这样的基础: / p>
I use this class as a base like this:
public class DerivedStringEnum : StringEnum
{
public static readonly DerivedStringEnum EnumValue1
= new DerivedStringEnum (0, "EnumValue1");
public static readonly DerivedStringEnum EnumValue2
= new DerivedStringEnum (1, "EnumValue2");
private DerivedStringEnum (int value, string name) : base(value, name) { }
}
但是,当我尝试使用
string s = "EnumValue1"
DerivedStringEnum e = (DerivedStringEnum) s;
返回一个InvalidCastException。检查代码显示StringEnum类的instances属性从未被填充。
An InvalidCastException is returned. Inspection of the code shows that the instances attribute of the StringEnum class is never filled.
有没有办法解决这个问题?
Is there an easy way to fix this?
我不喜欢使用[StringValue(EnumValue1)]的C#属性magic。
I prefer not to use C# attribute "magic" such as [StringValue("EnumValue1")].
谢谢!
推荐答案
您还必须在派生类上定义一个显式转换运算符。基类不会知道如何转换为派生类。
You have to define an explicit cast operator on the derived class as well. The base class is not expected to know how to cast to a derived class.
由于运算符是静态的,它们不被继承 - 显式转换运算符仅在 string
和 StringEnum
。你可以这样做比较丑陋的双重自己:
Since operators are static they are not inherited - the explicit cast operator is only defined between string
and StringEnum
. You can do this rather ugly double-cast yourself:
DerivedStringEnum e = (DerivedStringEnum)(StringEnum)s
或者在您的派生类中,您可以:(@ @指出我自己的监督之后编辑)
Or in your derived class you can put: (edited after @ili pointed out my own oversight)
public static explicit operator DerivedStringEnum(string name)
{
return (DerivedStringEnum)(StringEnum)name;
}
这篇关于使用用户定义的转换将字符串转换为类型安全枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!