c# - 使用反射设置时跳过只读属性
问题描述
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; }
}
此致
推荐阅读
- symfony - Symfony 4.1 - 应用程序仅在缓存被删除时才有效
- tensorflow - 在 Keras 中训练对象检测模型时出现不兼容张量形状的问题
- visual-studio-2017 - 如何使用面向 .NET Core 2.1.6 SDK 的 Visual Studio 2017 创建新项目
- spring-boot - spring boot actuator 自定义端点不允许可配置的端点 ID。示例:@Endpoint(id = "${mgmt.id.custom}")
- java - 如何从 Web 服务中获取字符串值并制作成微调器选定项?
- eclipse - Eclipse - 来自外部工具控制台输出的问题标记
- symfony-forms - Symfony 表单集合 - 保持与主键的关联
- docker - 尝试使用 bitbucket 管道在 docker 中调用服务的 url
- google-app-engine - Google App Engine - 使用外部目录中的种子文件部署?
- python - 从 urllib 和 Postman 调用时,Flask 服务器收到的 POST 请求数据的差异