相关疑难解决方法(0)

使用包含Type的变量创建Generic <T>类型实例

是否可以实现以下代码?我知道它不起作用,但我想知道是否有解决方法?

Type k = typeof(double);
List<k> lst = new List<k>();
Run Code Online (Sandbox Code Playgroud)

c# generics types instance

82
推荐指数
1
解决办法
4万
查看次数

通过反射设置属性Nullable <>

我尝试动态设置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总是空的

c# generics reflection nullable activator

12
推荐指数
3
解决办法
1万
查看次数

如何创建Nullable <T>的实例?

假设我们有两个类:

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)

c# linq generics reflection

6
推荐指数
1
解决办法
542
查看次数

标签 统计

c# ×3

generics ×3

reflection ×2

activator ×1

instance ×1

linq ×1

nullable ×1

types ×1