下面的代码与“ 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)
我想使用字节数组参数来操作此代码,同时保持其通用性。
希望您能帮助我解决此错误。
答案 0 :(得分: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()();
}
感谢您的评论。