我有一個很大的問題,我嘗試開發解析枚舉int值爲字符串值。我的參考書目是「http://weblogs.asp.net/stefansedich/archive/2008/03/12/enum-with-string-values-in-c.aspx」,但我有多個屬性2或3或4或45或100000000如何解析它?我寫了下面的代碼:但空引用異常:Vals [j] = item.GetType()。GetProperty(item.Name,BindingFlags.NonPublic | BindingFlags.Static).ToString();何必解決它?如何開發枚舉字符串解析擴展方法?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace EnumString
{
class Program
{
static void Main(string[] args)
{
String[] str = UserType.Login.GetStringValue();
//Console.WriteLine(UserType.Login.GetStringValue());
Console.Read();
}
}
public enum UserType : int
{
[StringValueAttribute("xyz", "test")]
Login = 1
}
public class StringValueAttribute : Attribute
{
public string UserName { get; protected set; }
public string PassWord { get; protected set; }
public decimal Something { get; protected set; }
public StringValueAttribute(string Username, string Password, decimal something)
{
UserName = Username;
PassWord = Password;
Something = something;
}
public StringValueAttribute(string Username, string Password)
{
UserName = Username;
PassWord = Password;
}
public StringValueAttribute(string Username)
{
UserName = Username;
}
}
public static class Extentions
{
public static String[] GetStringValue(this Enum value)
{
// Get the type
Type type = value.GetType();
// Get fieldinfo for this type
FieldInfo fieldInfo = type.GetField(value.ToString());
// Get the stringvalue attributes
StringValueAttribute[] attribs = fieldInfo.GetCustomAttributes(
typeof(StringValueAttribute), false) as StringValueAttribute[];
// Return the first if there was a match.
PropertyInfo[] pi = attribs[0].GetType().GetProperties();
String[] Vals = new String[pi.Length];
int j = 0;
foreach (PropertyInfo item in pi)
{
Vals[j] = item.GetType().GetProperty(item.Name, BindingFlags.NonPublic | BindingFlags.Static).ToString();
j++;
}
// i dislike return values one by one : attribs[0].UserName
return attribs.Length > 0 ? Vals : null; // i have more values
}
}
}
你的字符串值函數的行爲與調用Enum成員的默認.ToString()方法有什麼不同? – lsuarez
我想他想獲得所有重複值 –