我为接收字符串的字段做了自定义属性。 然后,我在枚举中使用custom属性。 我需要从FieldAttribute中获取“ MyMethod”的结果,但它不会返回字符串
这就是我所拥有的:
枚举和属性:
public enum CustomEnum
{
[Field("first field")]
Field1,
[Field("second field")]
Field2,
[Field("third field")]
Field3
}
[AttributeUsage(AttributeTargets.Field)]
public class FieldAttribute : Attribute
{
private string name;
public FieldAttribute(string name)
{
this.name = name;
}
public string LastName { get; set; }
public string MyMethod()
{
return this.name + this.LastName;
}
}
用法:
public class Program
{
public static void Main(string[] args)
{
PrintInfo(typeof(CustomEnum));
}
public static void PrintInfo(Type t)
{
Console.WriteLine($"Information for {t}");
Attribute[] attrs = Attribute.GetCustomAttributes(t);
foreach (Attribute attr in attrs)
{
if (attr is FieldAttribute)
{
FieldAttribute a = (FieldAttribute)attr;
Console.WriteLine($" {a.MyMethod()}");
}
}
}
}
请帮忙!!!
答案 0 :(得分:2)
它是这样的:
public static void PrintInfo(Type t)
{
Console.WriteLine($"Information for {t}");
var pairs =
from name in t.GetEnumNames()
let member = t.GetMember(name).Single()
let attr = (FieldAttribute)member.GetCustomAttributes(typeof(FieldAttribute), false)
.SingleOrDefault()
let text = attr.MyMethod()
select (name, text);
foreach (var (name, text) in pairs)
Console.WriteLine($"{name} -> {text}");
}
说明:您在类型上使用GetCustomAttributes
,但实际上需要确实为fields on the enum type的枚举常量。因此,您需要获取MemberInfo
作为枚举常量并要求其属性。
对于真正古老的编译器,您可以使用简单的
public static void PrintInfo(Type t)
{
Console.WriteLine($"Information for {t}");
foreach (string name in t.GetEnumNames())
{
MemberInfo member = t.GetMember(name).Single();
FieldAttribute attr =
(FieldAttribute)member.GetCustomAttributes(typeof(FieldAttribute), false)
.SingleOrDefault();
string text = attr.MyMethod();
Console.WriteLine(name + " -> " + text);
}
}