收录日期:2021/02/27 20:34:38 时间:2009-03-14 01:32:35 标签:c#
I'd like to have a simple helper method for converting a string to an Enum. Something like the following, but it doesn't like T as the first argument in the Enum.Parse. The error is T is a Type Parameter but is used like a variable.
public static T StringToEnum<T>(String value)
{
return (T) Enum.Parse(T,value,true) ;
}
Try this:
public static T StringToEnum<T>(String value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
public static T StringToEnum<T>(String value)
{
return (T) Enum.Parse(typeof(T),value,true) ;
}
What you were doing is like using 'int' as a Type, but it is not a Type object. To get the Type object, you would use typeof(int).
Here is a method extension I use.
/// <summary>
/// Will parse and string value and return the Enum given. Case is ignored when doing the parse.
/// </summary>
/// <param name="typeOfEnum">The type of the Enum to Parse</param>
/// <param name="value">The string value for the result of the Enum</param>
/// <param name="errorValue">If an error is encountered this value is returned. (For example could be an Enum)</param>
/// <returns>Returns Enum Object</returns>
public static T ToEnum<T>(this string value)
{
return (T)Enum.Parse(typeof(T), value, true);
}
C#, StringToEnum, can I make it a generic function out of this
Can I make this into a javascript function?
How can I write a generic C function for calling a Win32 function?
Problems with u201CISynchronizeInvokeu201D and u201Cthisu201D in C#. I think some sort of Invoke can fix it, but I can't work out how!
Can I pass a value out of a javascript function?
How can I make this java generic cast?
How can I make this extension method more generic?
How can I make this code more generic
How can I make a generic Clone factory method in C#?
How can I make an AJAX link work once it is moved out of the iFrame?
How can I make a type safe bag of items that all implement a generic interface?
How can I get my website to display a .c file instead of trying to make the user download it?
In jQuery, how can I make it so a click function can activate a resizable property
How can i make params `out` in C#?
How can I test the performance of a C function?
How can I make this Python recursive function return a flat list?
How can I solve out of memory exception in generic list generic?
How can I make this recursive crawl function iterative?