Enum.TryParse 方法

定义

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

重载

TryParse(Type, String, Boolean, Object)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse(Type, String, Object)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

TryParse<TEnum>(String, Boolean, TEnum)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 一个参数指定该操作是否区分大小写。A parameter specifies whether the operation is case-sensitive. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

TryParse<TEnum>(String, TEnum)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

TryParse(Type, String, Boolean, Object)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

public:
 static bool TryParse(Type ^ enumType, System::String ^ value, bool ignoreCase, [Runtime::InteropServices::Out] System::Object ^ % result);
public static bool TryParse (Type enumType, string value, bool ignoreCase, out object result);
static member TryParse : Type * string * bool * obj -> bool
Public Shared Function TryParse (enumType As Type, value As String, ignoreCase As Boolean, ByRef result As Object) As Boolean

参数

enumType
Type

用于分析的枚举类型。The enum type to use for parsing.

value
String

一个或多个枚举常量的名称或数值的字符串表示形式。The string representation of the name or numeric value of one or more enumerated constants.

ignoreCase
Boolean

若为 true,则在不区分大小写的模式下读取 value;若为 false,则在区分大小写的模式下读取 valuetrue to read value in case insensitive mode; false to read value in case sensitive mode.

result
Object

如果此方法返回 true,则为包含表示已分析值的枚举常量的对象。When this method returns true, an object containing an enumeration constant representing the parsed value.

返回

如果转换成功,则为 true;否则为 falsetrue if the conversion succeeded; false otherwise.

TryParse(Type, String, Object)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object.

public:
 static bool TryParse(Type ^ enumType, System::String ^ value, [Runtime::InteropServices::Out] System::Object ^ % result);
public static bool TryParse (Type enumType, string value, out object result);
static member TryParse : Type * string * obj -> bool
Public Shared Function TryParse (enumType As Type, value As String, ByRef result As Object) As Boolean

参数

enumType
Type

用于分析的枚举类型。The enum type to use for parsing.

value
String

一个或多个枚举常量的名称或数值的字符串表示形式。The string representation of the name or numeric value of one or more enumerated constants.

result
Object

如果此方法返回 true,则为包含表示已分析值的枚举常量的对象。When this method returns true, an object containing an enumeration constant representing the parsed value.

返回

如果转换成功,则为 true;否则为 falsetrue if the conversion succeeded; false otherwise.

TryParse<TEnum>(String, Boolean, TEnum)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 一个参数指定该操作是否区分大小写。A parameter specifies whether the operation is case-sensitive. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

public:
generic <typename TEnum>
 where TEnum : value class static bool TryParse(System::String ^ value, bool ignoreCase, [Runtime::InteropServices::Out] TEnum % result);
public static bool TryParse<TEnum> (string value, bool ignoreCase, out TEnum result) where TEnum : struct;
static member TryParse : string * bool * 'Enum -> bool (requires 'Enum : struct)
Public Shared Function TryParse(Of TEnum As Structure) (value As String, ignoreCase As Boolean, ByRef result As TEnum) As Boolean

类型参数

TEnum

要将 value 转换到的枚举类型。The enumeration type to which to convert value.

参数

value
String

要转换的枚举名称或基础值的字符串表示形式。The string representation of the enumeration name or underlying value to convert.

ignoreCase
Boolean

若要不区分大小写,则为 true;若要区分大小写,则为 falsetrue to ignore case; false to consider case.

result
TEnum

当此方法返回时,如果分析操作成功,result 将包含值由 value 表示的 TEnum 类型的对象。When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. 如果分析操作失败,result 将包含 TEnum 的基础类型的默认值。If the parse operation fails, result contains the default value of the underlying type of TEnum. 请注意,此值无需为 TEnum 枚举的成员。Note that this value need not be a member of the TEnum enumeration. 此参数未经初始化即被传递。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 value;否则为 falsetrue if the value parameter was converted successfully; otherwise, false.

异常

TEnum 不是枚举类型。TEnum is not an enumeration type.

示例

下面的示例定义了一个 Colors 枚举,调用 TryParse<TEnum>(String, Boolean, TEnum) 方法将字符串转换为其对应的枚举值,并调用 IsDefined 方法以确保特定整数值是中的基础值 Colors枚举.The following example defines a Colors enumeration, calls the TryParse<TEnum>(String, Boolean, TEnum) method to convert strings to their corresponding enumeration values, and calls the IsDefined method to ensure that particular integral values are underlying values in the Colors enumeration. 当尝试将命名常量的字符串表示形式转换为其等效的枚举值时,TryParse<TEnum>(String, Boolean, TEnum) 方法将使用不区分大小写的比较。The TryParse<TEnum>(String, Boolean, TEnum) method uses case-insensitive comparison when trying to convert the string representations of named constants to their equivalent enumeration values.

using System;

[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
   
public class Example
{
   public static void Main()
   {
      string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         Colors colorValue;
         if (Enum.TryParse(colorString, true, out colorValue))        
            if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))  
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
            else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
         else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
      }
   }
}
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       Converted 'blue' to Blue.
//       Converted 'Blue' to Blue.
//       Yellow is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.
<Flags> Enum Colors As Integer
   None = 0
   Red = 1
   Green = 2
   Blue = 4
End Enum

Module Example
   Public Sub Main()
      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}
      For Each colorString As String In colorStrings
         Dim colorValue As Colors
         If [Enum].TryParse(colorString, True, colorValue) Then        
            If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then 
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString())
            Else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString)            
            End If                    
         Else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'       Converted '0' to None.
'       Converted '2' to Green.
'       8 is not an underlying value of the Colors enumeration.
'       Converted 'blue' to Blue.
'       Converted 'Blue' to Blue.
'       Yellow is not a member of the Colors enumeration.
'       Converted 'Red, Green' to Red, Green.

注解

TryParse<TEnum>(String, Boolean, TEnum)Parse(Type, String, Boolean) 方法相同,不同之处在于,它在转换失败时返回 falseTryParse<TEnum>(String, Boolean, TEnum) is identical to the Parse(Type, String, Boolean) method, except that instead of throwing an exception, it returns false if the conversion fails. 它消除了分析枚举值的字符串表示形式时的异常处理需求。It eliminates the need for exception handling when parsing the string representation of an enumeration value.

value 参数包含枚举成员的基础值或命名常量的字符串表示形式,或者包含用逗号(,)分隔的命名常量或基础值的列表。The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants or underlying values delimited by commas (,). 如果 value 包含多个已命名的常量或值,则可以在 value中的每个值、名称或逗号的前面或后面加上一个或多个空格。If value includes multiple named constants or values, one or more blank spaces can precede or follow each value, name, or comma in value. 如果 value 是列表,result 会反映与按位 OR 运算组合在一起的指定名称或基础值的值。If value is a list, result reflects the value of the specified names or underlying values combined with a bitwise OR operation. 如果 value 是枚举值的名称的字符串表示形式,则 value 与枚举名称的比较取决于 ignoreCase 参数。If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names depends on the ignoreCase parameter. 如果 true,则比较不区分大小写;如果 false,则区分大小写。If true, the comparison is case-insensitive; if false, it is case-sensitive.

如果 value 是不对应于 TEnum的命名常数的名称,则该方法返回 falseIf value is a name that does not correspond to a named constant of TEnum, the method returns false. 如果 value 是整数的字符串表示形式,而该整数不表示 TEnum 枚举的基础值,则该方法将返回其基础值 value 转换为整型的枚举成员。If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. 如果不需要此行为,请调用 IsDefined 方法,以确保整数的特定字符串表示形式确实是 TEnum的成员。If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

另请参阅

TryParse<TEnum>(String, TEnum)

将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象。Converts the string representation of the name or numeric value of one or more enumerated constants to an equivalent enumerated object. 用于指示转换是否成功的返回值。The return value indicates whether the conversion succeeded.

public:
generic <typename TEnum>
 where TEnum : value class static bool TryParse(System::String ^ value, [Runtime::InteropServices::Out] TEnum % result);
public static bool TryParse<TEnum> (string value, out TEnum result) where TEnum : struct;
static member TryParse : string * 'Enum -> bool (requires 'Enum : struct)
Public Shared Function TryParse(Of TEnum As Structure) (value As String, ByRef result As TEnum) As Boolean

类型参数

TEnum

要将 value 转换到的枚举类型。The enumeration type to which to convert value.

参数

value
String

要转换的枚举名称或基础值的区分大小写字符串表示形式。The case-sensitive string representation of the enumeration name or underlying value to convert.

result
TEnum

当此方法返回时,如果分析操作成功,result 将包含值由 value 表示的 TEnum 类型的对象。When this method returns, result contains an object of type TEnum whose value is represented by value if the parse operation succeeds. 如果分析操作失败,result 将包含 TEnum 的基础类型的默认值。If the parse operation fails, result contains the default value of the underlying type of TEnum. 请注意,此值无需为 TEnum 枚举的成员。Note that this value need not be a member of the TEnum enumeration. 此参数未经初始化即被传递。This parameter is passed uninitialized.

返回

如果 true 参数成功转换,则为 value;否则为 falsetrue if the value parameter was converted successfully; otherwise, false.

异常

TEnum 不是枚举类型。TEnum is not an enumeration type.

示例

下面的示例定义了一个 Colors 枚举,调用 TryParse<TEnum>(String, TEnum) 方法将字符串转换为其对应的枚举值,并调用 IsDefined 方法以确保特定整数值是中的基础值 Colors枚举.The following example defines a Colors enumeration, calls the TryParse<TEnum>(String, TEnum) method to convert strings to their corresponding enumeration values, and calls the IsDefined method to ensure that particular integral values are underlying values in the Colors enumeration.

using System;

[Flags] enum Colors { None=0, Red = 1, Green = 2, Blue = 4 };
   
public class Example
{
   public static void Main()
   {
      string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };
      foreach (string colorString in colorStrings)
      {
         Colors colorValue;
         if (Enum.TryParse(colorString, out colorValue))        
            if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))  
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());
            else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);
         else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString);
      }
   }
}
// The example displays the following output:
//       Converted '0' to None.
//       Converted '2' to Green.
//       8 is not an underlying value of the Colors enumeration.
//       blue is not a member of the Colors enumeration.
//       Converted 'Blue' to Blue.
//       Yellow is not a member of the Colors enumeration.
//       Converted 'Red, Green' to Red, Green.
<Flags> Enum Colors As Integer
   None = 0
   Red = 1
   Green = 2
   Blue = 4
End Enum

Module Example
   Public Sub Main()
      Dim colorStrings() As String = {"0", "2", "8", "blue", "Blue", "Yellow", "Red, Green"}
      For Each colorString As String In colorStrings
         Dim colorValue As Colors
         If [Enum].TryParse(colorString, colorValue) Then        
            If [Enum].IsDefined(GetType(Colors), colorValue) Or colorValue.ToString().Contains(",") Then 
               Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString())
            Else
               Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString)            
            End If                    
         Else
            Console.WriteLine("{0} is not a member of the Colors enumeration.", colorString)
         End If
      Next
   End Sub
End Module
' The example displays the following output:
'    Converted '0' to None.
'    Converted '2' to Green.
'    8 is not an underlying value of the Colors enumeration.
'    blue is not a member of the Colors enumeration.
'    Converted 'Blue' to Blue.
'    Yellow is not a member of the Colors enumeration.
'    Converted 'Red, Green' to Red, Green.

注解

TryParse<TEnum>(String, TEnum)Parse(Type, String) 方法相同,不同之处在于,它在转换失败时返回 falseTryParse<TEnum>(String, TEnum) is identical to the Parse(Type, String) method, except that instead of throwing an exception, it returns false if the conversion fails. 它消除了分析枚举值的字符串表示形式时的异常处理需求。It eliminates the need for exception handling when parsing the string representation of an enumeration value.

value 参数包含枚举成员的基础值或命名常量的字符串表示形式,或者包含用逗号(,)分隔的命名常量或基础值的列表。The value parameter contains the string representation of an enumeration member's underlying value or named constant, or a list of named constants or underlying values delimited by commas (,). 如果 value 包含多个已命名的常量或值,则可以在 value中的每个值、名称或逗号的前面或后面加上一个或多个空格。If value includes multiple named constants or values, one or more blank spaces can precede or follow each value, name, or comma in value. 如果 value 是列表,result 会反映与按位 OR 运算组合在一起的指定名称或基础值的值。If value is a list, result reflects the value of the specified names or underlying values combined with a bitwise OR operation. 如果 value 是枚举值的名称的字符串表示形式,则与枚举名称 value 比较是区分大小写的。If value is the string representation of the name of an enumeration value, the comparison of value with enumeration names is case-sensitive.

如果 value 是不对应于 TEnum的命名常数的名称,则该方法返回 falseIf value is a name that does not correspond to a named constant of TEnum, the method returns false. 如果 value 是整数的字符串表示形式,而该整数不表示 TEnum 枚举的基础值,则该方法将返回其基础值 value 转换为整型的枚举成员。If value is the string representation of an integer that does not represent an underlying value of the TEnum enumeration, the method returns an enumeration member whose underlying value is value converted to an integral type. 如果不需要此行为,请调用 IsDefined 方法,以确保整数的特定字符串表示形式确实是 TEnum的成员。If this behavior is undesirable, call the IsDefined method to ensure that a particular string representation of an integer is actually a member of TEnum.

另请参阅

适用于