[英]Using reflection to get properties of an instance of a class at runtime C#
嗨,這是我想要做的,我有一個類(EventType),它可以是動態的,並在不同的時間有不同的成員/屬性。
class EventType
{
int id{set;}
string name{set;}
DateTime date{set;}
List<int> list{set;}
Guid guid{set;}
}
在我的main方法中,我將此類上的實例傳遞給另一個類中的函數,並嘗試使用反射來獲取實例的屬性但它不成功並給我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);
}
}
默認情況下,您的類屬性是私有的,而GetProperties
僅返回公共屬性。
將您的房產宣傳為公開:
class EventType
{
public int id{set;}
public string name{set;}
public DateTime date{set;}
public List<int> list{set;}
public Guid guid{set;}
}
或指定綁定閃存以獲取非公共屬性:
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
);
Type.GetProperties返回類型的公共屬性。 但是,由於您尚未指定屬性的訪問類型是否為私有 。
您可以使用重載的Type.GetProperties(BindingFlags)方法獲取所有屬性,無論其訪問修飾符如何。
Type.GetProperties
返回所有公共屬性,在您的類中它們都是私有的,因此不會返回它們。 您可以將它們公開,也可以使用BindingFlags
搜索私有文件,例如:
t.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);
class EventType
{
int id { get; set; }
string name { get; set; }
DateTime date { get; set; }
List<int> list { get; set; }
Guid guid { get; set; }
}
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(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.ToString());
}
//var bytes = serializer(input);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.