我有一个类
public class Stuff
{
public int A;
public float B;
public int C;
public float D;
public int E;
public List<float> AllMyFloats { get {/* how to grab B, D,... into new List<float>? */} }
}
如何获取一种类型的所有内容(例如给定示例中的 float
)并在属性访问时返回它们?
最佳答案
反射(reflection)是你的 friend 。
public class Stuff
{
public int A { get; set; }
public float B { get; set; }
public int C { get; set; }
public float D { get; set; }
public int E { get; set; }
public List<float> GetAllFloats()
{
var floatFields = GetType().GetProperties()
.Where(p => p.PropertyType == typeof(float));
return floatFields.Select(p => (float)p.GetValue(this)).ToList();
}
}
class Program
{
static void Main()
{
Stuff obj = new Stuff() { A = 1, B = 2, C = 3, D = 4, E = 5 };
obj.GetAllFloats().ForEach(f => Console.WriteLine(f));
Console.ReadKey();
}
}
输出:
2
4
关于c# - 如何获取具有给定类型的类实例的所有成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49997070/