代码之家  ›  专栏  ›  技术社区  ›  Mr. Smith

在C中使用反射获取字段的属性#

  •  3
  • Mr. Smith  · 技术社区  · 15 年前

    我编写了一个从如下对象中提取字段的方法:

    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”

    1 回复  |  直到 15 年前
        1
  •  15
  •   Community PPrice    4 年前

    GetCustomAttributes 方法返回一个 object[] HTMLAttributes[] . 它返回的原因 对象[] 它是从1.0开始出现的,在.NET泛型出现之前。

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

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

    foreach 我会帮你照看演员的。

    不应该 将返回的数组强制转换为 . 返回值不正确 HTMLAttributes[] . 这是一个 对象[] 包含类型为的元素 . 如果你想要一个 HTMLAttribute[] 类型化对象(在此特定代码段中不需要, 弗雷奇 就足够了),您应该将数组的每个元素分别强制转换为 HTMLAttribute

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