如何使用lambda表达式创建字节[]实例



下面的代码与" 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)

我想用字节数组参数操作此代码,同时保持其通用。

希望您可以帮助我解决此错误。

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

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()();
}

感谢您的评论。

相关内容

最新更新