[英]How to create an instance of byte[] with lambda expressions?
下面的代碼與“ 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()();
}
感謝您的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.