如何在C#/ .NET 4.0中编写带有delegate参数的方法?

cha*_*r m 6 .net c# delegates

我一直在使用我在类级别声明委托的方式:

protected delegate void FieldsDelegate();

//and then write a method e.g.

protected int CreateComponent(DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, FieldsDelegate fieldsDelegate)
Run Code Online (Sandbox Code Playgroud)

然而,这真的很麻烦,我无法立即看到代表是什么样的.所以我想这样做:

protected int CreateComponent(DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, delegate void fieldsDelegate())
Run Code Online (Sandbox Code Playgroud)

所以我没有单独的定义.

由于某种原因,不允许上述内容.那我该怎么办呢?

And*_*erd 12

.NET现在为此提供了ActionFunc泛型.

在您的情况下,此委托不接受任何参数并且不返回任何内容.

// protected delegate void FieldsDelegate(); // Don't need this anymore

protected int CreateComponent(
                               DbConnection cnctn, 
                               string tableName, 
                               Dictionary<string, object> changedFieldValues, 
                               Action fieldsDelegate
                            )
Run Code Online (Sandbox Code Playgroud)

如果它将一个字符串作为参数:

// protected delegate void FieldsDelegate(string s); 

protected int CreateComponent(
                               DbConnection cnctn, 
                               string tableName, 
                               Dictionary<string, object> changedFieldValues,
                               Action<string> fieldsDelegate
                             )
Run Code Online (Sandbox Code Playgroud)

如果它将一个字符串作为参数并返回一个bool:

// protected delegate bool FieldsDelegate(string s); 

protected int CreateComponent(
                               DbConnection cnctn, 
                               string tableName, 
                               Dictionary<string, object> changedFieldValues,
                               Func<string, bool> fieldsDelegate
                             )
Run Code Online (Sandbox Code Playgroud)


And*_*ber 5

您可以使用泛型Action<T>Func<T>它们的变体作为代理,并且奖励是您根本不需要定义单独的委托.

Action<T>需要多达16个不同类型的参数,所以:Action<T1, T2>和在最多; 每个类型参数都是相同位置的方法的类型参数.那么,Action<int, string>适用于这种方法:

public void MyMethod(int number, string info)
Run Code Online (Sandbox Code Playgroud)

Func<T>是相同的,除了它是返回值的方法.最后一个类型参数是返回类型.Func<T>这不是你在这里使用的.

示例:Func<string, int, object>将用于以下方法:

public object MyOtherMethod(string message, int number)
Run Code Online (Sandbox Code Playgroud)

使用这些泛型委托可以清楚地说明该委托参数的参数是什么,这似乎是您的意图.

public void MyMethod(Action<string, MyClass>, string message)
Run Code Online (Sandbox Code Playgroud)

调用该方法,你知道你需要传递一个带a string和a的方法MyClass.

public void MeOtherMethod(Func<int, MyOtherClass>, int iterations)
Run Code Online (Sandbox Code Playgroud)

在这里,您知道需要传递一个带int参数的方法,然后返回MyOtherClass