puede analizar el valor del atributo xml de nuevo a un tipo de enumeración con:
var value = Enum.Parse(typeof(Fuel), "B");
Pero no creo que obtendrá muy lejos con sus valores "especiales" (3
, a/
etc.). ¿Por qué no definir su enumeración como
enum Fuel
{
Benzine,
Diesel,
// ...
Three,
ASlash,
// ...
}
y escribir un método estático para convertir una cadena a un miembro de la enumeración?
Una cosa que podría considerar para implementar dicho método sería agregar atributos personalizados a los miembros enum que contienen su representación de cadena - si un valor no tiene una contraparte exacta en la enumeración, busque un miembro con la atributo.
Creación de un atributo tal es fácil:
/// <summary>
/// Simple attribute class for storing String Values
/// </summary>
public class StringValueAttribute : Attribute
{
public string Value { get; private set; }
public StringValueAttribute(string value)
{
Value = value;
}
}
y luego se puede utilizar en su enumeración:
enum Fuel
{
[StringValue("B")]
Benzine,
[StringValue("D")]
Diesel,
// ...
[StringValue("3")]
Three,
[StringValue("/")]
Slash,
// ...
}
Estos dos métodos le ayudarán a analizar una cadena en un miembro de la enumeración de su elección:
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value (case sensitive).
/// </summary>
public static object Parse(Type type, string stringValue)
{
return Parse(type, stringValue, false);
}
/// <summary>
/// Parses the supplied enum and string value to find an associated enum value.
/// </summary>
public static object Parse(Type type, string stringValue, bool ignoreCase)
{
object output = null;
string enumStringValue = null;
if (!type.IsEnum)
{
throw new ArgumentException(String.Format("Supplied type must be an Enum. Type was {0}", type));
}
//Look for our string value associated with fields in this enum
foreach (FieldInfo fi in type.GetFields())
{
//Check for our custom attribute
var attrs = fi.GetCustomAttributes(typeof (StringValueAttribute), false) as StringValueAttribute[];
if (attrs != null && attrs.Length > 0)
{
enumStringValue = attrs[0].Value;
}
//Check for equality then select actual enum value.
if (string.Compare(enumStringValue, stringValue, ignoreCase) == 0)
{
output = Enum.Parse(type, fi.Name);
break;
}
}
return output;
}
Y mientras estoy en ello: aquí es al revés;)
/// <summary>
/// Gets a string value for a particular enum value.
/// </summary>
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
if (StringValues.ContainsKey(value))
{
output = ((StringValueAttribute) StringValues[value]).Value;
}
else
{
//Look for our 'StringValueAttribute' in the field's custom attributes
FieldInfo fi = type.GetField(value.ToString());
var attributes = fi.GetCustomAttributes(typeof(StringValueAttribute), false);
if (attributes.Length > 0)
{
var attribute = (StringValueAttribute) attributes[0];
StringValues.Add(value, attribute);
output = attribute.Value;
}
}
return output;
}
que siga el enlace de abajo y me ha resultado útil. [En C#, deserializando enumeraciones de enteros.] (Http://stackoverflow.com/questions/9944421/c-sharp-deserializing-enums-from-integers/33387055#33387055) –