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

MJS*_*RMA 5 c# reflection

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

class EventType
{
    int id{set;}
    string name{set;}
    DateTime date{set;}
    List<int> list{set;}
    Guid guid{set;}
}
Run Code Online (Sandbox Code Playgroud)

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*e B 5

默认情况下,您的类属性是私有的,并且GetProperties仅返回公共属性。

要么将您的财产宣传为公开:

class EventType
{
    public int id{set;}
    public string name{set;}
    public DateTime date{set;}
    public List<int> list{set;}
    public Guid guid{set;}
}
Run Code Online (Sandbox Code Playgroud)

或者指定绑定flas来获取非公共属性:

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
    );
Run Code Online (Sandbox Code Playgroud)