简体   繁体   中英

Skipping properties that are read-only when setting using reflection

        public void ClickEdit(TItem clickedItem)
        {
            Crud = CrudEnum.Update;
            foreach (PropertyInfo prop in typeof(TItem).GetProperties())
            {
                prop.SetValue(EditItem, typeof(TItem).GetProperty(prop.Name).GetValue(clickedItem), null);
            }
        }

I created the above method to loop through an generic typed instance and use the value of that instance to set values in another instance of the same type.

However, some of the TItem properties are read-only, and then exceptions will be thrown.

What is the proper way to skip properties that are read-only and set only the properties that can be set?

Thanks!

you could try to check the CanWrite property:

    class Program
    {
        static void Main(string[] args)
        {
            Demo demo = new Demo();

            foreach (PropertyInfo property in demo.GetType().GetProperties())
            {
                if (property.CanWrite)
                {
                    property.SetValue(demo, "New value");
                }
            }
        }
    }

    public class Demo
    {
        public string ReadOnlyProperty { get; }

        public string ReadWriteProperty { get; set; }
    }   

Best regards

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