【问题标题】:Skipping properties that are read-only when setting using reflection使用反射设置时跳过只读属性
【发布时间】:2021-03-27 01:39:43
【问题描述】:
        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属性是只读的,然后会抛出异常。

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

谢谢!

【问题讨论】:

  • 请发布一个完整的例外或关闭问题as duplicate

标签: c# reflection properties


【解决方案1】:

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

最好的问候

【讨论】:

    猜你喜欢
    • 2018-02-07
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多