我有这段代码使用反射,我决定用 FastMember 替换它。
这是我的代码:
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;
}
}
}
通过反射:
带有星星的那一行将通过这一行来解决:
if (property?.CanWrite ?? false)
FastMember 是否也提供了一些优雅的解决方案?