为 Nullable 分配值使用 FastMember [英] Assign value to Nullable<T> using FastMember

查看:75
本文介绍了为 Nullable 分配值使用 FastMember的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用此函数成功地为属性和嵌套属性赋值

I have successfully assigned values to Properties and nested Properties using this function

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));
    }
}

但是,该赋值会引发 InvalidCastException.如何使用 FastMember 分配可空值?例如

However, the assignment throws an InvalidCastException. How to assign nullable values instead using FastMember? For example

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???

推荐答案

FastMember 在它的工具箱中与类型转换没有任何关系,所以这是我作为 FastMember ObjectAccessor 的扩展方法提出的解决方案:

FastMember has nothing related to type conversion within it's toolbox, so this is the solution I came up with as Extension Method for 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;
    }
}

可以这样调用:

var accessor = ObjectAccessor.Create(t); // t is instance of SomeType
accessor.AssignValueToProperty("Nested.Property", value); // t.Nested.Property = value

这篇关于为 Nullable 分配值使用 FastMember的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆