簡體   English   中英

轉換功能 <Type, object> 表達給Func <T> 其中T是一般約束

[英]Convert Func<Type, object> expression to Func<T> where T is generic constraint

我有這個靜態功能

public static object Create(Type t)
{
    //unimportant
}

我無法控制上述功能,因此無法更改。 問題是它不是通用的,因此我必須將返回的對象轉換為某種類型。 這種類型是由另一個通用類的約束提供的,在該通用類中,我將其稱為Create方法。

這是我到達的地方:

public static class Creator<T>
{
    public static void Create()
    {
        var m = typeof(SomeClass).GetMethod("Create");
        var p = Expression.Parameter(typeof(Type));
        var e = Expression.Call(m, p);

        //at this stage I want to create delegate for calling the 'Create' method, 
        //then pass typeof(T) as parameter, get returned object, 
        //and finally cast it to 'T'.

        //for eg, I can do it like this:
        var f = Expression.Lambda<Func<Type, object>>(e, p).Compile();
        Func<T> mainThing = () => (T)f(typeof(T));

        //is there a way I can achieve in one step?
    }
}

在我上面的方法中,我不是在編譯最終委托,而是先前的一個步驟。 如何在編譯之前也合並演員表並重新獲得Func<T>

您似乎正在經歷很多不必要的麻煩。 我不明白您為什么要通過表達式樹來執行此操作。 為什么不只是:

public static class Creator<T>
{
    public static void Create()
    {
        Func<T> mainThing = () => (T)SomeClass.Create(typeof(T));
    }
}

???

創建方法調用的表達式樹的目的僅是將其轉換回進行方法調用的委托,然后再調用它的目的是什么? 為什么不直接調用SomeClass.Create

我在這里想念什么嗎?

要回答您的實際問題:

在編譯之前,我也該如何合並演員表?

使用Expression.Convert()創建表示轉換的表達式樹節點。

我認為您只需要調用Expression.Convert ,並使用ConstantExpression而不是ParameterExpression

var method = typeof(SomeClass).GetMethod("Create");
var call = Expression.Call(method, Expression.Constant(typeof(T), typeof(Type)));
var conversion = Expression.Convert(call, typeof(T));
var function = Expression.Lambda<Func<T>>(conversion).Compile();

(我尚未測試過,但看起來還不錯...)

暫無
暫無

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

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