知道对象c#中的属性类型

Ton*_*Nam 3 c# reflection types properties

我知道如何使用反射获取对象属性:

var properties = typeof(T).GetProperties();
Run Code Online (Sandbox Code Playgroud)

现在我怎么知道properties [0]是否是一个字符串?或者它可能是一个int?我怎么知道?

Jon*_*eet 10

每个元素properties都是a PropertyInfo,它有一个PropertyType属性,表示属性的类型.

例如,您可以使用:

if (properties[0].PropertyType == typeof(string))
Run Code Online (Sandbox Code Playgroud)

或者如果您想以继承许可的方式检查某些内容:

if (typeof(Stream).IsAssignableFrom(properties[0].PropertyType))
Run Code Online (Sandbox Code Playgroud)