簡體   English   中英

獲取對象的所有類型的屬性

[英]Get all types of properties for an object

我有一個帶有某些類型的屬性的對象:

public class MyClass
{
    public List<SomeObj> List { get; set; }
    public int SomeKey { get; set; }
    public string SomeString { get; set; }
}

var obj = new MyClass();

MyClass obj實例獲取所有類型的屬性的最佳方法是什么?
例如:

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

如果您正在尋找更人性化的類型名稱,請參閱this

至於具有特定類型的屬性,則:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM