简体   繁体   English

C#反射:从类中检索静态对象

[英]C# Reflection: Retrieve Static Objects From a Class

My intention is to have a class T, that has several static readonly instances of its own type. 我的意图是拥有一个类T,该类具有自己类型的几个静态只读实例。 What I am now trying to do is to create a generic method that will recognize all those instances and add them to a list. 我现在想要做的是创建一个通用方法,该方法将识别所有这些实例并将它们添加到列表中。 So far I could locate all the elements, and the FieldInfo.FieldHandle.Value seems to contain the object, but I am yet unskilled in getting it. 到目前为止,我可以找到所有元素,并且FieldInfo.FieldHandle.Value似乎包含该对象,但是我对获取它仍然不熟练。 Maybe it is wrong to use FieldInfo. 也许使用FieldInfo是错误的。 Can anyone give me a hand? 有人可以帮我吗?

(Thanks!) Here is the code example (with solution applied): (谢谢!)这是代码示例(已应用解决方案):

using System;
using System.Collections.Generic;
using System.Reflection;

namespace PickStatic {
  class Fruit {
    public static readonly Fruit Orange = new Fruit("Orange");
    public static readonly Fruit Kiwi = new Fruit("Kiwi");
    public static readonly Fruit Pear = new Fruit("Pear");

    public string name { set; get; }

    public Fruit(string name) {
      this.name = name;
    }

    public static List<T> getAll<T>() where T : class {
      List<T> result = new List<T>();
      MemberInfo[] members = typeof(T).GetMembers();
      foreach(MemberInfo member in members) {
        if(member is FieldInfo) {
          FieldInfo field = (FieldInfo) member;
          if(field.FieldType == typeof(T)) {
            T t = (T) field.GetValue(null);
            result.Add(t);
          }
        }
      }
      return result;
    }

    public static void Main(string[] args) {
      List<Fruit> fruits = getAll<Fruit>();
      foreach(Fruit fruit in fruits) {
        Console.WriteLine("Loaded: {0}", fruit.name);
      }
      Console.ReadLine();
    }
  }
}

The class Fruit contains three static objects of type Fruit. 水果类包含三个水果类型的静态对象。 It is being attempted to get the list of all such objects using a generic method. 正在尝试使用泛型方法获取所有此类对象的列表。

You need to use the FieldInfo.GetValue method . 您需要使用FieldInfo.GetValue方法

Invoke it with null (Since it's a static field) 使用null调用它(因为它是一个静态字段)

Edit : It is not recommended to use reflection in "Critical" sections of the code (In terms of performance), You may use a Dictionary to cache the results returned from GetAll method. 编辑 :不建议在代码的“关键”部分中使用反射(就性能而言),您可以使用字典来缓存从GetAll方法返回的结果。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM