加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:32:37 所属栏目:百科 来源:网络整理
导读:我写了一个从对象中提取字段的方法,如下所示: private static string GetHTMLStatic(ref Object objectX,ref Liststring ExludeFields){ Type objectType = objectX.GetType(); FieldInfo[] fieldInfo = objectType.GetFields(); foreach (FieldInfo field
我写了一个从对象中提取字段的方法,如下所示:

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;

从我的理解(或缺乏),这应该工作?请扩展我的同事开发者!

*编辑,编译错误:

Cannot implicitly convert type
‘object[]’ to ‘data.HTMLAttributes[]’.
An explicit conversion exists (are you
missing a cast?)

我试过像这样投射它:

(HTMLAttributes)field.GetCustomAttributes(typeof(HTMLAttributes),false);

但是这也行不通,我得到了这个编译错误:

Cannot convert type ‘object[]’ to
‘data.HTMLAttributes’

解决方法

GetCustomAttributes方法返回一个对象[],而不是HTMLAttributes [].它返回object []的原因是它自1.0以来一直存在,在.NET泛型看到光之前.

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

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

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

foreach会为你照顾演员阵容.

更新:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读