在C#中使用反射获取字段的属性
-
07-07-2019 - |
题
我写了一个从像这样的对象中提取字段的方法:
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 []
。它是一个 object []
,包含 HTMLAttributes
类型的元素。如果你想要一个 HTMLAttribute []
类型的对象(在这个特定的代码片段中不需要, foreach
就足够了),你应该单独地将每个元素元素转换为<代码> HTMLAttribute 代码>;也许使用LINQ:
HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();