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

Getting the attributes of a field using reflection in C#(在 C# 中使用反射获取字段的属性)
本文介绍了在 C# 中使用反射获取字段的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个从这样的对象中提取字段的方法:

I wrote a method that extracts fields from an object like this:

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 循环中,我试图获取每个字段的属性及其各自的值.目前看起来是这样的:

Each field in my class also has it's own attributes, in this case my attribute is called HTMLAttributes. Inside the foreach loop I'm trying to get the attributes for each field and their respective values. It currently looks like this:

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() 方法中有一条红色波浪线:

This seems logical but it won't compile, I have a red squiggly line in the GetHTMLAttributes() method under:

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

我试图从中提取属性的字段位于另一个类中,如下所示:

The field I'm trying to extract the attributes from is in another class used like this:

[HTMLAttributes("input", "text")]
public string CustomerName;

根据我的理解(或缺乏理解),这应该有效吗?请各位开发者扩展我的思路!

From my understanding (or lack thereof) this should work? Please expand my mind fellow developers!

*编辑,编译器错误:

不能隐式转换类型'object[]' 到 'data.HTMLAttributes[]'.存在显式转换(您是缺少演员表?)

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

我试过这样投射:

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

但这也不起作用,我得到这个编译器错误:

But that also doesn't work, I get this compiler error:

无法将类型object[]"转换为'data.HTMLAttributes'

Cannot convert type 'object[]' to 'data.HTMLAttributes'

推荐答案

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

GetCustomAttributes method returns an object[], not HTMLAttributes[]. The reason it returns object[] is that it has been there since 1.0, before .NET generics see the light of day.

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

You should manually cast each item in the return value to HTMLAttributes.

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

To fix your code, you simply need to change the line to:

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

foreach 将为您处理演员表.

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

You shouldn't cast the returned array to HTMLAttributes[]. The return value is not HTMLAttributes[]. It's an object[] containing elements of type HTMLAttributes. If you want a HTMLAttribute[] typed object (which you don't need in this specific code snippet, foreach would suffice), you should cast each element of array individually to HTMLAttribute; perhaps using LINQ:

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

这篇关于在 C# 中使用反射获取字段的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)