可能重複:
C# How can I get the value of a string property via Reflection?
Get property value from string using reflection in C#通過字符串獲取屬性值
當我有一個字符串,我想用我的所有屬性名來進行比較。如果有匹配,我該如何返回此屬性的值?
類=設置
設置有2個屬性。
當我有一個字符串是與其中一個屬性名稱相同。我該如何返回該財產的價值?
謝謝。
可能重複:
C# How can I get the value of a string property via Reflection?
Get property value from string using reflection in C#通過字符串獲取屬性值
當我有一個字符串,我想用我的所有屬性名來進行比較。如果有匹配,我該如何返回此屬性的值?
類=設置
設置有2個屬性。
當我有一個字符串是與其中一個屬性名稱相同。我該如何返回該財產的價值?
謝謝。
您可以使用Reflection來讀取屬性名稱和值。例如,要得到一個類型的公共屬性的列表,你可以使用GetProperties方法:
var properties = typeof(Setting);
foreach (var prop in properties)
{
// here you can access the name of the property using prop.Name
// if you want to access the value you could use the prop.GetValue method
}
您可以使用反射來獲取你的類的屬性,你可以像一些事情做到這一點。
PropertyInfo[] propertyInfos;
propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
BindingFlags.Static);
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.Name == yourString)
{
return yourString;
}
}