c# - 在运行时使用反射获取类实例的属性 C#

标签 c# reflection

您好,这是我正在尝试做的,我有一个类 (EventType),它可以是动态的,并且在不同时间具有不同的成员/属性。

class EventType
{
    int id{set;}
    string name{set;}
    DateTime date{set;}
    List<int> list{set;}
    Guid guid{set;}
}

在我的主要方法中,我将此类上的一个实例传递给另一个类中的函数,并尝试通过反射来获取实例的属性,但它没有成功并给我 null 值。

class Program
{
    static void Main(string[] args)
    {
        EventType event1 = new EventType();
        int rate = 100;
        DataGenerator.Generate<EventType>(event1, rate);
    }
    public static byte[] test(EventType newEvent)
    {
        return new byte[1];
    }
}



static class DataGenerator
{
    public static void Generate<T>(T input, int eventRate, Func<T, byte[]> serializer=null)
    {            
        Type t = input.GetType();
        PropertyInfo[] properties = t.GetProperties();
        foreach (PropertyInfo property in properties)
        {
            Console.WriteLine(property.ToString());   
        }
        var bytes = serializer(input);
    }
}

最佳答案

您的类属性默认是私有(private)的,GetProperties 只返回公共(public)属性。

要么公开宣传您的属性(property):

class EventType
{
    public int id{set;}
    public string name{set;}
    public DateTime date{set;}
    public List<int> list{set;}
    public Guid guid{set;}
}

或指定绑定(bind) flas 以获取非公共(public)属性:

Type t = input.GetType();
PropertyInfo[] properties = t.GetProperties(
    BindingFlags.NonPublic | // Include protected and private properties
    BindingFlags.Public | // Also include public properties
    BindingFlags.Instance // Specify to retrieve non static properties
    );

关于c# - 在运行时使用反射获取类实例的属性 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16852758/

相关文章:

c# - 按特定项目对枚举类型列表的成员进行排序

c++ - 检查c++中是否存在函数时出现问题

c# - 使用标题信息获取图像的尺寸

c# - access sql 创建前检查索引是否存在

c# - 如何创建圆角 Panel 和 Clip bound

c# - 从 LINQ 查询批量更新?

Java:如何加载已经在类路径上的类(及其内部类)?

c# - “Object does not match target type” 用反射调用泛型方法时

java - 使用java反射覆盖复杂对象实例中的值

c# - 使用反射获取所有具有 Serializable 属性的扩展类型