且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#中显式转换字符串枚举

更新时间:2023-02-13 09:29:02

一个转换是不可能的。问题是,一个用户定义的转换必须用一个结构或类声明,并且转换必须是或从封闭类型。因此,

A cast is not possible. The issue is that a user-defined conversion must be enclosed in a struct or class declaration, and the conversion must be to or from the enclosing type. Thus,

public static explicit operator MyEnum(string value)

是不可能的,因为没有 MyEnum 字符串可以永远是封闭类型。

is impossible because neither MyEnum nor string can ever be the enclosing type.

在ECMA334 C#规范的相关部分17.9.4:

The relevant section of the ECMA334 C# spec is 17.9.4:

一个转换操作符从源类型,由转换的参数类型指示转换 操作者,到目标类型,由转换操作者的返回类型指示。类或结构是 允许定义从源类型S转换到目标类型T只有当以下所有的都是真实的, 其中,S0和T0是导致删除尾部的类型?改性剂,如果有的话,从S和T

A conversion operator converts from a source type, indicated by the parameter type of the conversion operator, to a target type, indicated by the return type of the conversion operator. A class or struct is permitted to declare a conversion from a source type S to a target type T only if all of the following are true, where S0 and T0 are the types that result from removing the trailing ? modifiers, if any, from S and T:

S0和T0是不同的类型。

S0 and T0 are different types.

无论是S0或T0是在运营商的声明发生在类或结构类型

无论是S0也不T0是一个接口类型。

Neither S0 nor T0 is an interface-type.

不包括用户自定义的转换,转换不选自S存在T或从T到秒。

Excluding user-defined conversions, a conversion does not exist from S to T or from T to S.

不过,您可以在string类做一个扩展方法。

However, you can do an extension method on the string class.

public static class StringExtensions {
    public static T ConvertToEnum<T>(this string value)  {
        Contract.Requires(typeof(T).IsEnum);
        Contract.Requires(value != null);
        Contract.Requires(Enum.IsDefined(typeof(T), value));
        return (T)Enum.Parse(typeof(T), value);
    }
}