簡體   English   中英

如何編寫一個C#方法來接受未知類型的注入依賴?

[英]How do I write a C# method that will accept an injected dependency of unknown type?

背景

我有幾個實用工具方法,我想添加到我正在工作的解決方案,並使用依賴注入將打開所述方法的更多潛在用途。

我正在使用C#,.NET 4

這是我想要完成的一個例子(這只是一個例子):

public static void PerformanceTest(Func<???> func, int iterations)
{
    var stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < iterations; i++)
    {
      var x = func();
    }
    stopWatch.Stop();

    Console.WriteLine(stopWatch.ElapsedMilliseconds);
}

我在這里做的是創建一個方法來測試我的代碼的某些元素在調試時的性能。 以下是如何使用它的示例:

Utilities.PerformanceTest(someObject.SomeCustomExtensionMethod(),1000000);

期望“PerformanceTest”方法傳遞(注入)已知類型的函數。 但是,如果我希望“PerformanceTest”能夠注入各種返回各種類型的函數呢? 我怎么做?

它不能只是通用的嗎?

public static void PerformanceTest<T>(Func<T> func, int iterations)
{
    var stopWatch = Stopwatch.StartNew();
    for (int i = 0; i < iterations; i++)
    {
        T x = func();
    }
    stopWatch.Stop();

    Console.WriteLine(stopWatch.ElapsedMilliseconds);
}

另外如果你不關心什么類型的參數,你可以傳遞Func<object> ,不是嗎?

我會將您的PerformanceTest方法更改為:

public static void PerformanceTest(Action func, int iterations)

結束比打電話:

Utilities.PerformanceTest(() => someObject.SomeCustomExtensionMethod(),1000000);

這可能會增加時間,因為lambda表達,但我不能說這是如何或如果這甚至是重要的,

使用泛型:

public static void PerformanceTest<T>(Func<T> func, int iterations)
{
    var stopWatch = new Stopwatch();
    stopWatch.Start();
    for (int i = 0; i < iterations; i++)
    {
      var x = func();
    }
    stopWatch.Stop();

    Console.WriteLine(stopWatch.ElapsedMilliseconds);
}

暫無
暫無

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

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