我有一個類Class1
獲取領域
public class Class1
{
public string ABC { get; set; }
public string DEF { get; set; }
public string GHI { get; set; }
public string JLK { get; set; }
}
我怎樣才能得到的名單,在這種情況下,「ABC」,「DEF」,... 我想獲取所有公共領域的名稱。
我試過如下:
Dictionary<string, string> props = new Dictionary<string, string>();
foreach (var prop in classType.GetType().GetProperties().Where(x => x.CanWrite == true).ToList())
{
//Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(classitem, null));
//objectItem.SetValue("ABC", "Test");
props.Add(prop.Name, "");
}
和:
var bindingFlags = BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public;
var fieldValues = classType.GetType()
.GetFields(bindingFlags)
.Select(field => field.GetValue(classType))
.ToList();
但無論是給了我想要的結果。
在此先感謝
只有''GetProperties()''應該可以工作 – 2015-04-01 16:43:27
什麼,具體來說,是不是你的嘗試解決方案的工作? – Servy 2015-04-01 16:44:17
看一看:[字段和C#中的屬性有什麼區別?](http://stackoverflow.com/questions/295104/what-is-the-difference-between-a-field-and-a -property-in-c) – 2015-04-01 16:46:55