好吧,我一直在努力寻找这方面的任何信息。我建立了一个小类来查看类型安全枚举对于字符串的实现有多难,因为我想将它们用于数据库字段名称等。我从不喜欢枚举只能用于整数的事实。
然而,即使我已经implicit operator
为这个类实现了一个,每次我尝试使用它时,它都会给我一个无效的强制转换异常。我很茫然,因为此时我的代码没有任何问题。
这是课程:
/// <summary>
/// SBool - type-safe-enum for boolean strings
/// </summary>
public sealed class SBool
{
private readonly String name;
private readonly int value;
// these guys were for conversions. They might work better in another case,
// but for this one, they weren't very helpful.
// ((I.e. they didn't work either.))
//private static readonly Dictionary<SBool, String> stringsByBool = new Dictionary<SBool, String>();
//private static readonly Dictionary<String, SBool> boolsByString = new Dictionary<String, SBool>();
public static readonly SBool True = new SBool( 1, "true" );
public static readonly SBool False = new SBool( 0, "false" );
private SBool( int value, String name )
{
this.name = name;
this.value = value;
//stringsByBool[this] = name;
//boolsByString[name] = this;
}
private SBool( SBool sbool )
{
this.name = sbool.name;
this.value = sbool.value;
//stringsByBool[this] = name;
//boolsByString[name] = this;
}
public override String ToString()
{
return name;
}
/// <summary>
/// allows implicit casting of SBools to strings
/// </summary>
/// <param name="sbool">the SBool to cast into a string</param>
/// <returns>the string equivalent of the SBool (its value)</returns>
public static implicit operator String( SBool sbool )
{
if ( sbool == SBool.True )
return SBool.True.name;
else
return SBool.False.name;
}
/// <summary>
/// implicitly cast a string into a SBool.
/// </summary>
/// <param name="str">the string to attempt to cast as a SBool</param>
/// <returns>the SBool equivalent of the string,
/// SBool.False if not either "true" or "false".</returns>
public static explicit operator SBool( String str )
{
if ( !String.IsNullOrEmpty(str) && str.ToLower() == "true" )
return SBool.True;
else
return SBool.False;
}
public static bool operator ==( SBool left, SBool right )
{
return left.value == right.value;
}
public static bool operator !=( SBool left, SBool right )
{
return left.value != right.value;
}
}
这在检查 Session 变量时失败:
if( ( (string)Session["variable"] ) == SBool.False )
带有 InvalidCastException,
坦率地说,我不知道为什么。
提前致谢; 任何人都可以解释为什么这不起作用的 cookie(cookie 并非在所有地区都可用)。我将解决其他问题,但如果有任何不清楚的地方,请告诉我。有关类型安全枚举的更多信息,这是我基于此类的 SO 帖子之一。
[MetaEDIT] 忽略这一点。我大错特错,大错特错。[/编辑]