C#中显式转换字符串枚举 [英] C# explicit cast string to enum

查看:144
本文介绍了C#中显式转换字符串枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有间有明确的转换,从一个字符串在C#中的枚举,才能有这样的:

I would like to have an explicit cast between from a string to an enum in c# in order to have this :

(MyEnum) Enum.Parse(typeof(MyEnum),stringValue)

我想驱逐到这一点有明确的转换操作符,我这样做,但没有奏效:

I would like to deport this into an explicit cast operator, I did this but didn't work :

public static explicit operator (MyEnum)(value stringValue){
     return (MyEnum) Enum.Parse(typeof(MyEnum),stringValue);
}

你知道,如果它使用.NET 3.5可能在C#?

Do you know if it's possible in C# using .NET 3.5?

推荐答案

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

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);
    }
}

这篇关于C#中显式转换字符串枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆