【问题标题】:How to create an instance of byte[] with lambda expressions?如何使用 lambda 表达式创建 byte[] 的实例?
【发布时间】: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


【解决方案1】:

这是即使使用字节数组也能保持通用对象生成的解决方案。

T instance;

if (!typeof(T).IsArray)
{
    ConstructorInfo constructorInfo = typeof(T).GetConstructor(Type.EmptyTypes);
    NewExpression newExpression = Expression.New(constructorInfo);
    instance = Expression.Lambda<Func<T>>(newExpression).Compile()();
}
else
{
    NewArrayExpression newArrayExpression = Expression.NewArrayBounds(typeof(T).GetElementType(), Expression.Constant(0));
    instance = Expression.Lambda<Func<T>>(newArrayExpression).Compile()();
}

感谢你们的 cmets 伙计们。

【讨论】:

  • 您好,您应该接受自己的答案,这样其他有相同问题的人一眼就能看出它已经回答了。
  • @ckuri,是的,这是计划好的,但我必须在提出问题后等待 2 天。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多