简体   繁体   中英

Set objects properties from string in C#

Is there any way to set the properties of the objects from string. For example I have "FullRowSelect=true" and "HoverSelection=true" statements as string for ListView property.

How to assign these property along with their values without using if-else or switch-case statments? Is there any SetProperty(propertyName,Value) method or similar for this?

Try this:

private void setProperty(object containingObject, string propertyName, object newValue)
{
    containingObject.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, containingObject, new object[] { newValue });
}

You can do this with reflection, have a look at the PropertyInfo class's SetValue method

 YourClass theObject = this;
 PropertyInfo piInstance = typeof(YourClass).GetProperty("PropertyName");
 piInstance.SetValue(theObject, "Value", null);

您可以使用反射来做到这一点:

myObj.GetType().GetProperty("FullRowSelect").SetValue(myObj, true, null);

Try this:

PropertyInfo pinfo = this.myListView.GetType().GetProperty("FullRowSelect");
if (pinfo != null)
    pinfo.SetValue(this.myListView, true, null);

没有这种方法,但是您可以使用Reflection编写一个。

You can look at Reflection . Its possible to find property and set its value thanks to this. But you need to parse your string yourself. And it may be problem geting valid value of correct type from string.

这可以通过反思来实现,例如看这个问题

First variant is to use 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;
        }
    }

to get a property value:

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

You can also use Expression class to access properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM