私はあなたのアイデアを開いています:私は本当にこの使用法が嫌いです。属性を使ってenumを文字列に変換する方法しかし、私の質問StringValueAttributeには複数のコンストラクタがあることに注意してください。どのようにStringValueAttributeを介してGetStringValue拡張メソッドを開発するか?敬具は...属性を持つ列挙型の使用方法Reflections?
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