[英]Getting the attributes of a field using reflection in C#
我写了一个从对象中提取字段的方法,如下所示:
private static string GetHTMLStatic(ref Object objectX, ref List<string> ExludeFields)
{
Type objectType = objectX.GetType();
FieldInfo[] fieldInfo = objectType.GetFields();
foreach (FieldInfo field in fieldInfo)
{
if(!ExludeFields.Contains(field.Name))
{
DisplayOutput += GetHTMLAttributes(field);
}
}
return DisplayOutput;
}
我班级中的每个字段也都有自己的属性,在这种情况下,我的属性称为HTMLAttributes。 在foreach循环中,我试图获取每个字段的属性及其各自的值。 它目前看起来像这样:
private static string GetHTMLAttributes(FieldInfo field)
{
string AttributeOutput = string.Empty;
HTMLAttributes[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
foreach (HTMLAttributes fa in htmlAttributes)
{
//Do stuff with the field's attributes here.
}
return AttributeOutput;
}
我的属性类看起来像这样:
[AttributeUsage(AttributeTargets.Field,
AllowMultiple = true)]
public class HTMLAttributes : System.Attribute
{
public string fieldType;
public string inputType;
public HTMLAttributes(string fType, string iType)
{
fieldType = fType.ToString();
inputType = iType.ToString();
}
}
这似乎是合乎逻辑的但它不会编译,我在GetHTMLAttributes()方法中有一条红色的波浪线:
field.GetCustomAttributes(typeof(HTMLAttributes), false);
我试图从中提取属性的字段在另一个类中使用,如下所示:
[HTMLAttributes("input", "text")]
public string CustomerName;
从我的理解(或缺乏),这应该工作? 请扩展我的同事开发者!
*编辑,编译错误 :
无法将类型'object []'隐式转换为'data.HTMLAttributes []'。 存在显式转换(您是否错过了演员?)
我试过像这样投射它:
(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);
但是这也行不通,我得到了这个编译错误:
无法将'object []'类型转换为'data.HTMLAttributes'
GetCustomAttributes
方法返回一个object[]
,而不是HTMLAttributes[]
。 它返回object[]
的原因是它自1.0以来一直存在,在.NET泛型看到光之前。
您应该手动将返回值中的每个项目转换为HTMLAttributes
。
要修复代码,只需将行更改为:
object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
foreach
会为你照顾演员阵容。
您不应该将返回的数组HTMLAttributes[]
为HTMLAttributes[]
。 返回值不是HTMLAttributes[]
。 它是一个包含HTMLAttributes
类型元素的object[]
。 如果你想要一个HTMLAttribute[]
类型的对象(在这个特定的代码片段中不需要, foreach
就足够了),你应该将数组的每个元素单独地HTMLAttribute
为HTMLAttribute
; 也许使用LINQ:
HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.