【问题标题】:Get all types of properties for an object获取对象的所有类型的属性
【发布时间】:2016-07-13 13:48:16
【问题描述】:

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

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

【问题讨论】:

  • obj.GetType().GetProperties();

标签: c#


【解决方案1】:

使用反射:

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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-19
    • 2011-01-24
    • 1970-01-01
    • 2011-09-20
    • 2012-01-28
    相关资源
    最近更新 更多