我编写了一个从如下对象中提取字段的方法:
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;
}
类中的每个字段也有自己的属性,在本例中,我的属性称为HtmlatAttributes。在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;
根据我的理解(或缺乏理解),这应该有效吗?请各位开发人员拓展我的思路!
*编辑,编译器错误
:
无法隐式转换类型
存在一个显式转换(您是吗
缺少演员阵容?)
我试过这样铸造它:
(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);
“data.HTMLAttributes”