Mr.*_*ith 3 c# reflection attributes fieldinfo
我写了一个从对象中提取字段的方法,如下所示:
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;
}
Run Code Online (Sandbox Code Playgroud)
我班级中的每个字段也都有自己的属性,在这种情况下,我的属性称为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;
}
Run Code Online (Sandbox Code Playgroud)
我的属性类看起来像这样:
[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();
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎是合乎逻辑的但它不会编译,我在GetHTMLAttributes()方法中有一条红色的波浪线:
field.GetCustomAttributes(typeof(HTMLAttributes), false);
Run Code Online (Sandbox Code Playgroud)
我试图从中提取属性的字段是在另一个类中使用,如下所示:
[HTMLAttributes("input", "text")]
public string CustomerName;
Run Code Online (Sandbox Code Playgroud)
从我的理解(或缺乏),这应该工作?请扩展我的同事开发者!
*编辑,编译错误:
无法将类型'object []'隐式转换为'data.HTMLAttributes []'.存在显式转换(您是否错过了演员?)
我试过像这样投射它:
(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes), false);
Run Code Online (Sandbox Code Playgroud)
但是这也行不通,我得到了这个编译错误:
无法将'object []'类型转换为'data.HTMLAttributes'
Meh*_*ari 14
GetCustomAttributes方法返回一个object[],而不是HTMLAttributes[].它返回的原因object[]是它自1.0以来一直存在,在.NET泛型看到光明之前.
您应该手动将返回值中的每个项目转换为HTMLAttributes.
要修复代码,只需将行更改为:
object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);
Run Code Online (Sandbox Code Playgroud)
foreach 将为您照顾演员阵容.
您不应该将返回的数组强制转换为HTMLAttributes[].返回值不是HTMLAttributes[].它object[]包含类型的元素HTMLAttributes.如果你想要一个HTMLAttribute[]类型化的对象(在这个特定的代码片段中你不需要foreach它就足够了),你应该将数组的每个元素单独地转换为HTMLAttribute; 也许使用LINQ:
HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();
Run Code Online (Sandbox Code Playgroud)