如何获取给定类型的 class 实例的所有成员?

How to grab all members of a class instance with a given type?

我有一个 class 喜欢

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)并在 属性 访问时 return 它们?

你可以为此使用反射。
一些伪代码:

public List<float> AllMyFloats
{ 
    get
    {
        var allMyFloats = new List<float>();

        var properties = this.GetType().GetProperties();
        foreach (var property in properties)
        {
            if (property.PropertyType == typeof(float))
            {
                //Get the value for the property on the current instance
                allMyFloats.Add(property.GetValue(this, null));
            }
        }

        return allMyFloats;
    }
 }

反思是你的朋友。

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