我打開你的想法:我真的不喜歡這種用法。如何通過屬性將枚舉轉換爲字符串。但請小心我的問題StringValueAttribute也有不止一個構造函數字段。如何通過StringValueAttribute開發GetStringValue擴展方法?順祝商祺...如何使用枚舉的屬性思考?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace UsingAttributes
{
static void Main(string[] args)
{
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 i = 0;
foreach (PropertyInfo item in pi)
{
// Vals[i] = How to return String[]
}
// i dislike return values one by one : attribs[0].UserName
//return attribs.Length > 0 ? attribs[0].UserName : null; // i have more values
}
}
}
但我不知道用戶名,密碼什麼的 – programmerist
然後,只需添加一個功能到屬性類,它給你的信息。如果這是不可能的,只需添加一些反射調用來獲取值。 – JaCraig