[英]Set objects properties from string in C#
有什么方法可以從字符串設置對象的屬性。 例如,我有“ FullRowSelect = true”和“ HoverSelection = true”語句作為ListView屬性的字符串。
如何在不使用if-else或switch-case語句的情況下分配這些屬性及其值? 是否有任何SetProperty(propertyName,Value)
方法或類似的方法?
嘗試這個:
private void setProperty(object containingObject, string propertyName, object newValue)
{
containingObject.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, containingObject, new object[] { newValue });
}
您可以通過反射進行操作,看看PropertyInfo類的SetValue方法
YourClass theObject = this;
PropertyInfo piInstance = typeof(YourClass).GetProperty("PropertyName");
piInstance.SetValue(theObject, "Value", null);
您可以使用反射來做到這一點:
myObj.GetType().GetProperty("FullRowSelect").SetValue(myObj, true, null);
嘗試這個:
PropertyInfo pinfo = this.myListView.GetType().GetProperty("FullRowSelect");
if (pinfo != null)
pinfo.SetValue(this.myListView, true, null);
沒有這種方法,但是您可以使用Reflection編寫一個。
您可以看一下反射 。 由此可以找到屬性並設置其值。 但是您需要自己解析字符串。 從字符串中獲取正確類型的有效值可能是問題。
這可以通過反思來實現,例如看這個問題 。
第一種方法是使用反射:
public class PropertyWrapper<T>
{
private Dictionary<string, MethodBase> _getters = new Dictionary<string, MethodBase>();
public PropertyWrapper()
{
foreach (var item in typeof(T).GetProperties())
{
if (!item.CanRead)
continue;
_getters.Add(item.Name, item.GetGetMethod());
}
}
public string GetValue(T instance, string name)
{
MethodBase getter;
if (_getters.TryGetValue(name, out getter))
return getter.Invoke(instance, null).ToString();
return string.Empty;
}
}
獲得屬性值:
var wrapper = new PropertyWrapper<MyObject>(); //keep it as a member variable in your form
var myObject = new MyObject{LastName = "Arne");
var value = wrapper.GetValue(myObject, "LastName");
您還可以使用Expression
類訪問屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.