C# 如何使用反射来实例将ReadOnlySpan作为构造函数参数的类?
我有这样的代码:C# 如何使用反射来实例将ReadOnlySpan作为构造函数参数的类?,c#,reflection,C#,Reflection,我有这样的代码: // lookup the object type, instance passing the data as constructor //all registered types must implement ctor passed ReadOnlySpan<byte> public static object InterpretPayload(ReadOnlySpan<byte> bytes) { va
// lookup the object type, instance passing the data as constructor
//all registered types must implement ctor passed ReadOnlySpan<byte>
public static object InterpretPayload(ReadOnlySpan<byte> bytes)
{
var key = bytes[0];
if (!TypeLookup.ContainsKey(key))
return null;
Type type = TypeLookup[key];
var created = Activator.CreateInstance(type, bytes);
return created;
}
TypeLookup以一种奇怪的工厂方法模式将数值映射到类类型。然而,当将代码库更改为使用ReadOnlySpan over byte[]时,我现在得到一个编译器错误,即bytes不是对象,而它不是
还有别的办法吗?我相信Activator会根据我传入的内容找到最好的ctor,似乎我需要更明确地这样做。我是否可以用另一种方式使用反射,或者我是否发现案例反射无法模拟直接调用ctor?您必须使用反射来获得相对强类型的委托,这样ReadOnlySpan实例就可以在不使用装箱的情况下传递,这是由于magic特殊案例生命周期管理而不允许的 从以下示例开始:
您可能希望在类型查找中缓存delegateCtor对象,而不是每次都重新创建它。您必须使用反射来获取相对强类型的委托,以便可以在不使用装箱的情况下传递ReadOnlySpan实例,这是由于magic特殊情况下的生存期管理而不允许的 从以下示例开始: 您可能希望在类型查找中缓存delegateCtor对象,而不是每次都重新创建它
using System.Linq.Expressions;
// Creating a parameter for the expression tree.
ParameterExpression param = Expression.Parameter(typeof(ReadOnlySpan<byte>));
// get your type
// get your ConstructorInfo by calling type.GetConstructor(...)
// Creating an expression for the constructor call and specifying its parameter.
var ctorCall = Expression.New(type, ctorinfo, param);
// The following statement first creates an expression tree,
// then compiles it, and then runs it.
var delegateCtor = Expression.Lambda<Func<ReadOnlySpan<byte>,object>>(
ctorCall, new ParameterExpression[] { param }).Compile();
// call it
var created = delegateCtor(bytes);