My intention is to have a class T, that has several static readonly instances of its own type. 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. Maybe it is wrong to use 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 .
Invoke it with null
(Since it's a static field)
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.