我的意图是有一个类 T,它有几个自己类型的静态只读实例。我现在要做的是创建一个通用方法来识别所有这些实例并将它们添加到列表中。到目前为止,我可以找到所有元素,并且 FieldInfo.FieldHandle.Value 似乎包含该对象,但我在获取它方面还不够熟练。也许使用 FieldInfo 是错误的。谁能帮我一把?
(谢谢!)这是代码示例(应用了解决方案):
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();
}
}
}
Fruit 类包含三个 Fruit 类型的静态对象。正在尝试使用通用方法获取所有此类对象的列表。