是否可以实现以下代码?我知道它不起作用,但我想知道是否有解决方法?
Type k = typeof(double);
List<k> lst = new List<k>();
Run Code Online (Sandbox Code Playgroud) 我尝试动态设置Nullable <>属性.
我得到我的房产前:
PropertyInfo property = class.GetProperty("PropertyName"); // My property is Nullable<> at this time So the type could be a string or int
Run Code Online (Sandbox Code Playgroud)
我想用反射来设置我的属性
property.SetValue(class,"1256",null);
Run Code Online (Sandbox Code Playgroud)
当我的属性是Nullable <> Generic时,它不起作用.所以我试图找到一种方法来设置我的财产.
要知道我执行的可以为空的<>属性的类型
Nullable.GetUnderlyingType(property.PropertyType)
Run Code Online (Sandbox Code Playgroud)
任何的想法 ?
我尝试用我的Nullable <>属性创建一个实例
var nullVar = Activator.CreateInstance(typeof(Nullable <>).MakeGenericType(new Type [] {Nullable.GetUnderlyingType(property.PropertyType)}));
但是nullVar总是空的
假设我们有两个类:
public class ParentEntity
{
public ChildEntity Child { get; set; }
}
public class ChildEntity
{
public byte? NullableValue { get; set; }
public byte Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
任务是在linq表达式中表达以下代码:
parent.Child == null ? null : parent.Child.NullableValue
Run Code Online (Sandbox Code Playgroud)
为此,我尝试使用以下代码:
public static Expression GetCondition<TParent, TChild, TChildKey>(
Expression<Func<TParent, TChild>> pe,
Expression<Func<TChild, TChildKey>> ce)
{
var test = Expression.Equal(pe.Body, Expression.Constant(null));
var ifTrue = Expression.Constant(Activator.CreateInstance<TChildKey>());
var ifFalse = Expression.Property(pe.Body,
(ce.Body as MemberExpression).Member.Name);
return Expression.Condition(test, ifTrue, ifFalse);
}
Run Code Online (Sandbox Code Playgroud)
运行此代码
Expression<Func<ParentEntity, ChildEntity>> pe = …Run Code Online (Sandbox Code Playgroud)