如何通过反射设置Nullable<T>
值?
我能够设置不是Nullable<T>
的值,并检测类型是否为Nullable<T>
类型,但我找不到如何正确设置此值的方法。
这是当前的片段:
public bool SetProperty(string propertyLambdaString, object value)
{
try
{
ParameterExpression paramParty = Expression.Parameter(typeof(TModel), "model");
MemberExpression property = BuildPropertyExpression(paramParty, propertyLambdaString);
ParameterExpression paramValue = Expression.Parameter(value.GetType(), "value");
if (Nullable.GetUnderlyingType(property.Type) != null)
{
// TODO: Question: How to assign a value to a nullable? Assign throws exception.
//Expression assignmentExp = Expression.Assign(property, paramValue);
//LambdaExpression lambda = Expression.Lambda(
// assignmentExp,
// new List<ParameterExpression> { paramParty, paramValue });
//lambda.Compile().DynamicInvoke(this.model, value);
return false;
}
// TODO: Question: How to set a value to null?
Expression assignmentExp = Expression.Assign(property, paramValue);
LambdaExpression lambda = Expression.Lambda(
assignmentExp,
new List<ParameterExpression> { paramParty, paramValue });
lambda.Compile().DynamicInvoke(this.model, value);
}
catch (Exception exception)
{
Logger.Error(exception);
return false;
}
return true;
}
// find delimiters and build MemberExpression for nested properties
private static MemberExpression BuildPropertyExpression(Expression param, string propertyLambdaString)
{
int firstDelim = propertyLambdaString.IndexOf('.');
if (firstDelim < 0)
{
return Expression.Property(param, propertyLambdaString);
}
string head = propertyLambdaString.Substring(0, firstDelim);
string tail = propertyLambdaString.Substring(firstDelim + 1);
MemberExpression expr = BuildPropertyExpression(param, head);
return BuildPropertyExpression(expr, tail);
}