我有一个包含某些类型属性的对象:
public class MyClass
{
public List<SomeObj> List { get; set; }
public int SomeKey { get; set; }
public string SomeString { get; set; }
}
var obj = new MyClass();
获取obj
MyClass
个实例的所有类型属性的最佳方法是什么?
例如:
obj.GetAllPropertiesTypes() //int, string, List<>
obj.HasPropertyType("int") //True
答案 0 :(得分:2)
使用反思:
var obj = new MyClass();
foreach (var prop in obj.GetType().GetProperties())
{
Console.WriteLine($"Name = {prop.Name} ** Type = { prop.PropertyType}");
}
结果:
Name = List ** Type = System.Collections.Generic.List`1[NameSpaceSample.SomeObj]
Name = SomeKey ** Type = System.Int32
Name = SomeString ** Type = System.String
如果您正在寻找更多用户友好型类型名称,请参阅this。
至于具有特定类型的属性,则:
bool hasInt = obj.GetType().GetProperties().Any(prop => prop.PropertyType == typeof(int));