简体   繁体   English

如何使用反射获取与特定类型匹配的对象字段的值列表?

[英]How do I use reflection to get a list of values of an object's fields that match a particular type?

Please note that for conciseness and readability, I've substituted types, fields, and methods that are more simple to work with. 请注意,为了简洁和可读性,我已替换了更易于使用的类型,字段和方法。

I've defined a boolean property, personProperty for a class, Person , in which I want the getter, get{} to call a private method, personMethod(int arg) on each integer field value that's defined in Person (in this case _age , _phoneNumber ). 我已经为类Person定义了一个布尔属性personProperty ,在该类中我希望getter get{}对在Person中定义的每个整数字段值(在本例中为_age personMethod(int arg)调用私有方法personMethod(int arg)_phoneNumber )。 It should ignore all other types like readingList . 它应该忽略所有其他类型,如readingList

This is so that if I were to add another integer field to Person (or modify or delete any Person field names), I would not have to update the definition of personProperty which, by design choice, depends on all integer fields of the Person class (ie, it is never the case that the developer will introduce an int field that he doesn't want personMethod to run against). 这样,如果我要向Person添加另一个整数字段(或修改或删除任何Person字段名称),则不必更新personProperty的定义,根据设计选择,该定义取决于Person类的所有整数字段(即,永远不会让开发人员引入一个他不想让personMethod运行的int字段)。

public Class Person
{
   private int _age;
   public int _phoneNumber;
   // protected int _futureInt;
   Dictionary<string, string> _readingList = new Dictionary<string, string>();

   public bool personProperty
   {
       get
       {
           // ...
           bool personPropertyReturnValue; 
           List<bool> resultList = new List<bool>();
           foreach(int personFieldValue in LISTOFPERSONINTS)
           {
               bool result = personMethod(personFieldValue);
               resultList.Add(result);
           }
           // Do stuff with `resultList` that'll initialize personPropertyReturnValue;
           return personPropertyReturnValue;
       }
   }

    private bool personMethod(int arg)
    {
       bool returnValue = true;
       // Do stuff to initialize `returnValue`
       return returnValue;
    }
}

I need to know what I should substitute for LISTOFPERSONINTS so that it returns an iterable over the values stored in _age , _phoneNumber (and all other future int , like _futureInt defined in Person ). 我需要知道我应该代替LISTOFPERSONINTS ,使其返回了存储在值的迭代_age_phoneNumber (以及其他所有未来int ,像_futureInt中定义Person )。

I don't think that using reflection would be better than adjusting your property each time you add a field, but there you go: 我不认为使用反射会比每次添加字段来调整属性都要好,但是您可以:

public class Person
{
    private int _age;
    public int _phoneNumber;
    // protected int _futureInt;
    Dictionary<string, string> _readingList = new Dictionary<string, string>();

    public Person(int age){
        _age = age;
    }

    public bool personProperty
    {
        get
        {
            List<bool> resultList = new List<bool>();
            var intFields = this.GetType().GetFields(BindingFlags.Instance | 
                                                     BindingFlags.NonPublic | 
                                                     BindingFlags.Public)
                                          .Where(f => f.FieldType == typeof(int))
                                          .Select(f => f.GetValue(this)).Cast<int>();
            foreach (int personFieldValue in intFields)
            {
                bool result = personMethod(personFieldValue);
                resultList.Add(result);
            }
            // Do stuff with `resultList` that'll initialize personPropertyReturnValue;
            bool personPropertyReturnValue = resultList.All(b => b);
            return personPropertyReturnValue;
        }
    }

    private bool personMethod(int arg)
    {
        return (arg > 0);
    }
}

Test: 测试:

var person1 = new Person(0);
Console.WriteLine(person1.personProperty);   // False

var person2 = new Person(1);
Console.WriteLine(person2.personProperty);   // False

var person3 = new Person(1) { _phoneNumber = 1 };
Console.WriteLine(person3.personProperty);   // True

反思:如何从 object 中获取值作为列表<object><div id="text_translate"><p>使用反射,我需要一个接受通用对象列表并打印其值的 function</p><pre> List&lt;Gender&gt; genders = new List&lt;Gender&gt; { new Gender { Id: 1, Name: "Male" }, new Gender { Id: 2, Name: "Female" } } PrintListValues(genders, "Name"); // prints Male, Female</pre><p> PrintListValues 必须接受列表为 object。 并且该列表可以包含任何类型的 object。 只要通用 object 有属性传入,它应该打印列表中每个项目的值。</p><pre> public static void PrintValues(object listObject) { // code here }</pre><p> 不幸的是,这就是项目要求的方式。</p><p> 一直在为这个问题挠头,无法弄清楚。 反思对我来说太难了。 如果有人可以给我提示,那就太好了!</p></div></object> - Reflection: how to get values from object as List<object>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Reflection获取特定接口类型的所有字段 - How can I use Reflection to get all fields of particular interface type 如何使用反射来获取方法的字段? - How do I use Reflection to get the fields of a method? 如何使用Reflection设置类型为List <CustomClass>的Property - How do I use Reflection to set a Property with a type of List<CustomClass> 如何使用反射获取特定类型的通用列表 - How to use reflection to get generic lists of a particular type 使用 C# 反射,如果该对象是列表内的对象的属性,则如何获取该对象的属性及其值 - Using C# Reflection, how to get Object's properties and their values if that Object is a property of Object that is inside of the List 如何在列表中获取特定的派生对象 <T> ? - How do I get a particular derived object in a List<T>? 如何使用反射将类型对象转换为C#中的列表。 我可以访问对象中的属性,但不能访问值,有什么建议吗? - how do I convert Type Object to a List in C# with reflection. I can access the properties in the object but cannot access the values, any suggestions? 反思:如何从 object 中获取值作为列表<object><div id="text_translate"><p>使用反射,我需要一个接受通用对象列表并打印其值的 function</p><pre> List&lt;Gender&gt; genders = new List&lt;Gender&gt; { new Gender { Id: 1, Name: "Male" }, new Gender { Id: 2, Name: "Female" } } PrintListValues(genders, "Name"); // prints Male, Female</pre><p> PrintListValues 必须接受列表为 object。 并且该列表可以包含任何类型的 object。 只要通用 object 有属性传入,它应该打印列表中每个项目的值。</p><pre> public static void PrintValues(object listObject) { // code here }</pre><p> 不幸的是,这就是项目要求的方式。</p><p> 一直在为这个问题挠头,无法弄清楚。 反思对我来说太难了。 如果有人可以给我提示,那就太好了!</p></div></object> - Reflection: how to get values from object as List<object> 如何通过反射获取委托类型的返回类型? - How do I get the return type of a delegate type through reflection? 如何使用反射来获取对象实例的公共属性? - How to use reflection to get just the object instance's public properties?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM