C#反射:查找属性的一个成员字段 [英] C# Reflection : Finding Attributes on a Member Field

查看:225
本文介绍了C#反射:查找属性的一个成员字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能会错误地问这个,但能/你怎么能找到自己在一类领域...例如...

I may be asking this incorrectly, but can/how can you find fields on a class within itself... for example...

public class HtmlPart {
  public void Render() {
    //this.GetType().GetCustomAttributes(typeof(OptionalAttribute), false);
  }
}

public class HtmlForm {
  private HtmlPart _FirstPart = new HtmlPart();      
  [Optional] //<-- how do I find that?
  private HtmlPart _SecondPart = new HtmlPart();
}

或者,也许我只是在做这个错误...我怎么能调用一个方法,然后检查是否有适用于自身的属性?

Or maybe I'm just doing this incorrectly... How can I call a method and then check for attributes applied to itself?

另外,对于这个问题的缘故 - !我只是好奇,如果有可能找到属性信息的不知道/访问父类

Also, for the sake of the question - I'm just curious if it was possible to find attribute information without knowing/accessing the parent class!

推荐答案

如果我正确地理解你的问题,我想你正在尝试做的是不可能的...

If I understand your question correctly, I think what you are trying to do is not possible...

渲染方法,你想要得到应用到该对象的可能的属性。该属性属于字段 _SecondPart 女巫属于类的HtmlForm

In the Render method, you want to get a possible attribute applied to the object. The attribute belongs to the field _SecondPart witch belongs to the class HtmlForm.

有关的工作,你就必须调用对象传递给渲染方法:

For that to work you would have to pass the calling object to the Render method:

    public class HtmlPart {
        public void Render(object obj) {
            FieldInfo[] infos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            foreach (var fi in infos)
            {
                if (fi.GetValue(obj) == this && fi.IsDefined(typeof(OptionalAttribute), true))
                    Console.WriteLine("Optional is Defined");
            }
        }
    }

这篇关于C#反射:查找属性的一个成员字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆