Bea*_*ker 3 c# nullable properties fastmember
我已使用此函数成功将值分配给Properties和嵌套属性
private static void AssignValueToProperty(ObjectAccessor accessor, object value, string propertyLambdaString)
{
var index = propertyLambdaString.IndexOf('.');
if (index == -1)
{
accessor[propertyLambdaString] = value;
// problem above: throws Exception if assigning value to Nullable<T>
}
else
{
var property = propertyLambdaString.Substring(0, index);
accessor = ObjectAccessor.Create(accessor[property]);
AssignValueToProperty(accessor, value, propertyLambdaString.Substring(index + 1));
}
}
Run Code Online (Sandbox Code Playgroud)
但是,赋值会抛出InvalidCastException.如何使用FastMember指定可空值?例如
public class A
{
public double? SomeValue {get; set;}
}
...
var a = new A();
var accessor = ObjectAccessor.Create(a);
accessor["SomeValue"] = 100; // throws Exception, when assigning 100.0 it works???
Run Code Online (Sandbox Code Playgroud)
FastMember与其工具箱中的类型转换没有任何关系,所以这就是我作为FastMember的扩展方法提出的解决方案ObjectAccessor:
public static class FastMemberExtensions
{
public static void AssignValueToProperty(this ObjectAccessor accessor, string propertyName, object value)
{
var index = propertyName.IndexOf('.');
if (index == -1)
{
var targetType = Expression.Parameter(accessor.Target.GetType());
var property = Expression.Property(targetType, propertyName);
var type = property.Type;
type = Nullable.GetUnderlyingType(type) ?? type;
value = value == null ? GetDefault(type) : Convert.ChangeType(value, type);
accessor[propertyName] = value;
}
else
{
accessor = ObjectAccessor.Create(accessor[propertyName.Substring(0, index)]);
AssignValueToProperty(accessor, propertyName.Substring(index + 1), value);
}
}
private static object GetDefault(Type type)
{
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
}
Run Code Online (Sandbox Code Playgroud)
可以这样调用:
var accessor = ObjectAccessor.Create(t); // t is instance of SomeType
accessor.AssignValueToProperty("Nested.Property", value); // t.Nested.Property = value
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
583 次 |
| 最近记录: |