gpt4 book ai didi

c# - 使用 FastMember 为 Nullable 赋值

转载 作者:行者123 更新时间:2023-11-30 13:54:40 26 4
gpt4 key购买 nike

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

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

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 的扩展方法:

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

关于c# - 使用 FastMember 为 Nullable<T> 赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com