簡體   English   中英

如何使用反射來實例化一個將 ReadOnlySpan 作為構造函數參數的類?

[英]How can I use reflection to instance a class which takes ReadOnlySpan as a constructor argument?

我有這樣的代碼:

    // 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以一種奇怪的工廠方法模式將數值映射到類類型。 但是,當更改我的代碼庫以在byte[]上使用ReadOnlySpan ,我現在收到一個編譯器錯誤,即bytes不是對象,而事實並非如此。

有沒有另一種方法可以做到這一點? 我相信Activator根據我傳入的內容嘗試找到最好的 ctor,似乎我需要更明確地做到這一點。 我可以用另一種方式使用反射,還是我發現一個案例反射不能直接模擬調用 ctor?

您必須使用反射來獲取(相對)強類型委托,以便可以在不裝箱的情況下傳遞ReadOnlySpan實例(由於特殊的特殊生命周期管理,這種類型不允許)

Expression.Parameter的示例開始:

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

您可能希望在類型查找中緩存delegateCtor對象,而不是每次都重新創建它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM