【问题标题】:Getting the attributes of a field using reflection in C#在 C# 中使用反射获取字段的属性
【发布时间】: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


【解决方案1】:

GetCustomAttributes 方法返回 object[],而不是 HTMLAttributes[]。它返回 object[] 的原因是它从 1.0 开始就存在,在 .NET 泛型出现之前。

您应该手动将返回值中的每个项目强制转换为HTMLAttributes

要修复您的代码,您只需将行更改为:

object[] htmlAttributes = field.GetCustomAttributes(typeof(HTMLAttributes), false);

foreach 会为您安排演员。

更新:

不应该将返回的数组转换为HTMLAttributes[]。返回值不是HTMLAttributes[]。这是一个object[],包含HTMLAttributes 类型的元素。如果你想要一个 HTMLAttribute[] 类型的对象(在这个特定的代码 sn-p 中不需要,foreach 就足够了),你应该将数组的每个元素单独转换为 HTMLAttribute;也许使用 LINQ:

HTMLAttributes[] htmlAttributes = returnValue.Cast<HTMLAttributes>().ToArray();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 2011-10-06
    • 2011-02-15
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多