簡體   English   中英

如何在沒有類型參數的情況下調用Func?

[英]How to invoke Func with without type arguments?

請注意,我的邏輯是復雜的,我已經簡化了一切,專注於這個問題。

我有函數字典,我必須調用,但函數將類型T作為輸入參數,它是派生類型,我沒有訪問權限,它可以是運行時的任何東西。 我該如何調用它?

我得到以下錯誤,

Unable to cast object of type 
 'System.Func`2[DerivedClass,System.String]' to type    
 'System.Func`2[BaseClass,System.String]'.

我嘗試過的替代品,我已經知道了,我正在尋找更好的性能,然后是以下備選方案。

  1. 使用動態
  2. 重新創建表達式樹,然后動態編譯和執行

兩種選擇都非常昂貴,我需要更簡單的方法。

這不是關於為什么我得到這個編譯器錯誤,或者我是否需要重新設計我的應用程序的問題,當我已經說過我有兩個調用Func的替代方案時,我正在尋找第三個更簡單的替代方案,如果存在

如何在不訪問DerivedClass的情況下調用Func<DerivedClass,String> 我和我有一個對象。

class Program
{
    static void Main(string[] args)
    {

        object input = new DerivedClass();

        Func<BaseClass, string> f = null;

        Func<DerivedClass, string> a = s => s.ToString();

        object obj = a;

        // ERROR
        f = (Func<BaseClass, string>)obj;

        Console.WriteLine(f(input));

        Console.ReadLine();

    }
}


public class BaseClass {
    public override string ToString()
    {
        return "Base Class";
    }
}

public class DerivedClass : BaseClass {

    public override string ToString()
    {
        return "Derived Class";
    }

}

你在這里嘗試做的事情並沒有多大意義。 假設您有一個A類,以及兩個繼承自它的B和C類。

如果你能夠做你在這里說的話然后使用函數Func<B, string>並將其轉換為Func<A, string>將意味着你得到一個函數,它也可以將C的實例作為參數C也繼承自A.

實際上,您可以更進一步地說,因為所有內容都從對象繼承,您可以將任何函數轉換為Func<object, string> ,然后將您想要的任何內容作為參數傳遞。

讓我們擺脫代表們一秒鍾,並根據他們抽象的方法來考慮這一點。 考慮以下Foo方法:

public static void Foo(int i)
{
    Console.WriteLine(i + 2);
}

現在我們有另一種方法Bar 它接受一個object 我們想在參數上調用Foo

public static void Bar(object o)
{
    Foo(o);
}

當然,這不起作用。 我們無法知道提供的對象實際上是一個int

這通常意味着兩件事之一:

  1. 你實際上並不想這樣做; 你無法知道更通用的參數實際上是一個正確的更多派生參數的實例; 你應該重新設計你的應用程序。

  2. 您知道編譯器沒有的東西,雖然編譯器無法驗證此約束是否正確,但實際上它在運行時無論出於何種原因都是有效的。 由於您知道它不會失敗,您可以使用強制轉換來通知編譯器,並將類型檢查推遲到運行時。

如果你碰巧在這里的第二個位置而不是第一個位置,你可以不通過強制轉換委托來添加強制轉換,而是通過創建一個新方法(可能通過lambda)對參數執行強制轉換然后調用另一位代表:

Func<DerivedClass, string> derivedSelector = derived => derived.ToString();

Func<BaseClass, string> baseSelector = s => derivedSelector((DerivedClass)s);

暫無
暫無

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

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