我编写了一个方法,从对象中提取字段,就像这样:
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'