跳过使用反射设置时只读的属性

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

我创建了上述方法来遍历泛型类型实例,并使用该实例的值来设置相同类型的另一个实例中的值。

但是TItem的部分属性是只读的,会抛出异常

跳过只读属性并只设置可设置属性的正确方法是什么?

谢谢!

您可以尝试检查 CanWrite 属性:

    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; }
    }   

此致