c# - 如何获取具有给定类型的类实例的所有成员?

标签 c# .net reflection c#-5.0

我有一个类

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/

相关文章:

.net - Azure Monitor - REST API 自定义日志 - .Net

c# - 如何使用反射获取基础构造函数调用参数

c# - 如何在.Net中以中间层结构化方式处理错误或异常

c# - 如何验证 SMTP 服务器

java - 通过反射获取java注解信息

java - java中的随机值取决于字段类型

c# - 从 C# 中的 List<T> 中选择 N 个随机元素

c# - 带有扩展的 Protocol Buffer

c# - 异步调用机制设计c#

c# - 在控制台应用程序中使用 SendGrid