获取对象的所有类型的属性

本文关键字:类型 属性 取对象 获取 | 更新日期: 2023-09-27 17:56:36

我有一个具有某些类型属性的对象:

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

获取对象的所有类型的属性

使用反射:

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

如果您正在寻找更多用户友好的类型名称,请参阅此处。

至于特定类型的 Has 属性,则:

bool hasInt = obj.GetType().GetProperties().Any(prop => prop.PropertyType == typeof(int));