【发布时间】:2009-09-13 12:44:39
【问题描述】:
我写了一个从这样的对象中提取字段的方法:
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'
【问题讨论】:
-
我你会告诉我们你遇到了哪个错误,也许有人可以帮忙..
-
更新了编译器错误的问题。
标签: c# reflection attributes fieldinfo