[英]Check whether property is readonly
I have this code using reflection and I decided to replace it by FastMember. 我有使用反射的这段代码,我决定将其替换为FastMember。
This is my code: 这是我的代码:
var VehicleType = TypeAccessor.Create(res.GetType());
var vehicleFastMember = ObjectAccessor.Create(res);
foreach (var kvp in dictionary)
{
if (kvp.Key == "Identifier") continue;
object value = kvp.Value;
if (VehicleType.GetMembers().FirstOrDefault(prop => prop.Name == kvp.Key) != null)
{
// here inside if i want to check whether property is not readonly,
// I am afraid of runtime exception that readonly cannot be overwritten.
**if (vehicleFastMember[kvp.Key].)**
{
vehicleFastMember[kvp.Key] = kvp.Value;
}
}
}
By reflection: 通过反思:
That row with stars would be solved by this line: 带有星号的行将通过以下行解决:
if (property?.CanWrite ?? false)
Does FastMember offer some elegant solution too? FastMember也提供一些优雅的解决方案吗?
According to the source code of fast-member's MemberSet.Member, CanRead/CanWrite are calling the same methods you are trying to call (PropertyInfo.Can[Read/Write]). 根据快速成员的MemberSet.Member 的源代码 ,CanRead / CanWrite会调用您尝试调用的相同方法(PropertyInfo.Can [Read / Write])。
It's also worth noting that instead of determining if the property is writable, you could simply wrap the assignment into a try/catch, and catch the ReadOnlyException that would emerge and continue with the loop. 还值得注意的是,您无需确定该属性是否可写,而只需将分配包装到try / catch中,并捕获将出现的ReadOnlyException并继续循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.