在C#中使用reflection获取字段的属性
我写了一个从对象中提取字段的方法,如下所示:
private static string GetHTMLStatic(ref Object objectX, ref List 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以来一直存在,在.NETgenerics看到光之前。
您应该手动将返回值中的每个项目转换为HTMLAttributes
。
要修复代码,只需将行更改为:
object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
foreach
会为你照顾演员阵容。
更新:
您不应该将返回的数组HTMLAttributes[]
为HTMLAttributes[]
。 返回值不是HTMLAttributes[]
。 它是一个包含HTMLAttributes
类型元素的object[]
。 如果你想要一个HTMLAttribute[]
类型的对象(在这个特定的代码片段中你不需要, foreach
就足够了),你应该将数组的每个元素单独地HTMLAttribute
为HTMLAttribute
; 也许使用LINQ:
HTMLAttributes[] htmlAttributes = returnValue.Cast().ToArray();