[英]Retrieve value from field attribute C#
我创建了一些自定义属性以将其应用于 class 成员:
[
System.AttributeUsage(
AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true
)
]
internal class ActionAttribute : Attribute
{
private Action action;
public ActionAttribute(Action action)
{
this.action = action;
}
public Action getThis()
{
return this.action;
}
}
但是我正在努力如何使用反射来检索它的价值。
这是我的尝试:
public static Device Serialize(string deviceName, Dictionary<string, dynamic> fields)
{
var itce = devices[deviceName];
Type objectType = itce.GetType();
MemberInfo[] fieldsInfo = objectType.GetMembers();
foreach (var field in fieldsInfo.Where(p => p.MemberType == MemberTypes.Property))
{
Console.WriteLine(field.Name);
object[] actionAttributes = field.GetCustomAttributes(typeof(ActionAttribute), false);
foreach (var cAttr in actionAttributes)
{
Console.WriteLine("Attrs: " + cAttr.GetType());
}
}
return itce;
}
在变量itce
中,我只是使用工厂模式检索包含这些属性的类型的先前分配的实例。
我想要的是实际值,但我只能读取它的 class 定义全名。 很明显,我要求它提供给GetType()
方法,但我只有四个可用的选项,比如ToString()
和类似的东西。 我想我可能错过了一些类型转换? 不知道。 希望有人可以帮助我。
顺便说一句, Action
类型只是一个枚举:
enum Action
{
Read,
Write
}
并且,一个简单的属性使用示例:
public class Device : Display
{
[Action(Action.Read)]
[Action(Action.Write)]
public string device_name { get; set; }
public Device(string device_name)
{
this.device_name = device_name;
}
}
所以,这个想法是,只要一个类型有一个带注释的字段,就检索属性的值。 上面, Device
有两个注解, Read
和Write
。 我想通过反射恢复附加到该字段的实际值或值。
device_name 有两个属性,所以我需要恢复Action.Read
和Action.Write
。
谢谢。
正如@freakish 指出的那样,解决方案非常简单。
object[] actionAttributes = field.GetCustomAttributes(typeof(ActionAttribute), false);
foreach (var cAttr in actionAttributes)
{
var attr = (ActionAttribute)cAttr;
Console.WriteLine("Attrs: " + attr.getThis());
}
将var cAttr
转换为属性类型可以让我轻松访问包含字段属性的信息。
不要将var
用作循环控制变量并且它是object
,而是将类型指定为您的属性:
object[] actionAttributes = field.GetCustomAttributes(typeof(ActionAttribute), false);
foreach (ActionAttribute cAttr in actionAttributes)
{
Console.WriteLine("Attrs: " + cAttr.getThis());
}
当然,您确实应该使用公共只读属性,而不是私有字段和方法来访问该值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.