簡體   English   中英

如何將函數傳遞給具有不同參數的函數並執行它c#

[英]how to pass a function to a function with different parameters and execute it c#

我有一個C#應用程序。

我有幾個不同的函數,具有不同的返回類型和傳遞給每個函數的不同參數。

我知道我可以這樣做:

public object RunTheMethod(Func<string, int> myMethodName)
{
    //... do stuff
    int i = myMethodName("My String");
    //... do more stuff
    return true;
}

但我可能有兩個我想要傳遞的功能。

第一個功能就像這個例子所示。 它接受一個字符串並返回一個int。 但是,如果我想傳遞一個對象或根本沒有參數怎么辦?

這里有什么通用選項。

謝謝

@PEOPLE我在這里有很多好建議。 這就是我喜歡這個網站的原因。 我需要自己動手,喝杯茶,徹底看看這些建議。

我保證會回應。

謝謝大家!

一個選項是使函數參數不帶參數:

public bool RunTheMethod(Func<int> f)
{
    //... do stuff
    int i = f();
    //... do more stuff
    return true;
}

然后,在調用RunTheMethod ,您可以捕獲lambda表達式中的其他參數,如下所示:

var b1 = RunTheMethod(() => theFunctionThatTakesAString("foo"));
var b2 = RunTheMethod(() => theFunctionThatTakesTwoIntegers(42, 1337));

如果您希望能夠改變輸出類型,可以將RunTheMethod通用本身,如下所示:

public bool RunTheMethod<T>(Func<T> f)
{
    //... do stuff
    T x = f();
    //... do more stuff
    return true;
}

然而,在這一點上,輸入參數是否是函數是否真的有意義是一個問題。 我注意到這個問題用功能編程標記了; 在FP中,一個更慣用的設計,那就是簡單地讓方法取值:

public bool RunTheMethod<T>(T x)
{
    //... do stuff
    // no need to call a function to get x; you already have x
    //... do more stuff
    return true;
}

然后,調用方法(或函數)也變得更容易:

var b1 = RunTheMethod(theFunctionThatTakesAString("foo"));
var b2 = RunTheMethod(theFunctionThatTakesTwoIntegers(42, 1337));

如果您需要將值作為函數,因為您希望能夠控制何時進行求值,請考慮使用Lazy<T>

實際上你需要執行任意Action而不是Func

public object RunTheMethod(Action myMethod)
{
    //... do stuff
    myMethod();
    //... do more stuff
    return true;
}

RunTheMethod(() => Sing("La la la"));

我想你想以這種方式調用泛型方法:

public object Execute(MethodInfo mi, object instance = null, object[] parameters = null)
{
    return mi.Invoke(instance, parameters);
}

所以你的方法需要將這些作為參數。

也許這些代碼可以幫到你。

   public T Common<T>(Func<T> action)
    {
        //do something log or watch
        try
        {
            return action();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
        finally
        {
        }
    }

    public Int32 Run(string query)
    {
        //Set whatever type you want. Or extend generic parameters
        return Common<Int32>(() =>
        {
            return 1;
        });
    }

暫無
暫無

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

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