首页 > 解决方案 > 使用反射设置时跳过只读属性

问题描述

        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 属性是只读的,然后会抛出异常。

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

谢谢!

标签: c#reflectionproperties

解决方案


您可以尝试检查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; }
    }   

此致


推荐阅读