【发布时间】:2019-02-25 14:24:58
【问题描述】:
下面的代码与“T”参数中的许多对象完美配合。
ConstructorInfo constructorInfo = typeof(T).GetConstructor(Type.EmptyTypes);
NewExpression newExpression = Expression.New(constructorInfo);
dynamic instance = Expression.Lambda<Func<dynamic>>(newExpression).Compile()();
但是,如果 "T" 是 byte[],则会发生异常。
ArgumentNullException: Value cannot be null. Parameter name: construtor at Expression.New(ConstructorInfo consctructor)
我想用字节数组参数操作这段代码,同时保持它的通用性。
希望你能帮我解决这个错误。
【问题讨论】:
-
byte[]没有构造函数,它是一个数组。比如你不能写var x = new byte[]() -
如果你有 byte[] 那么 lambda 表达式需要以 ToArray() 结尾,并且从 lambda 返回的类型也需要是 byte[]。
-
如果它是一个数组(即
typeof(T).IsArray),你需要做Expression.NewArrayBounds(typeof(T).GetElementType(), Expression.Constant(0))。另外,当您知道它是T时,我不明白您为什么要返回dynamic。 -
谢谢@ckuri。它完美无缺!我将重构的代码用于回答我的问题。
标签: c# arrays lambda reflection expression