c# - 如何在 C#/.NET 4.0 中编写带有委托(delegate)参数的方法?

标签 c# .net delegates

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

protected delegate void FieldsDelegate();

//and then write a method e.g.

protected int CreateComponent(DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, FieldsDelegate fieldsDelegate)

然而,这真的很麻烦,我无法立即看到委托(delegate)是什么样的。所以我想这样做:

protected int CreateComponent(DbConnection cnctn, string tableName, Dictionary<string, object> changedFieldValues, delegate void fieldsDelegate())

所以我没有单独的定义。

由于某些原因,上述内容是不允许的。那我该怎么做呢?

最佳答案

.NET 现在提供 ActionFunc用于此目的的泛型。

在您的情况下,此委托(delegate)不接受任何参数且不返回任何内容。

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

protected int CreateComponent(
                               DbConnection cnctn, 
                               string tableName, 
                               Dictionary<string, object> changedFieldValues, 
                               Action fieldsDelegate
                            )

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

// protected delegate void FieldsDelegate(string s); 

protected int CreateComponent(
                               DbConnection cnctn, 
                               string tableName, 
                               Dictionary<string, object> changedFieldValues,
                               Action<string> fieldsDelegate
                             )

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

// protected delegate bool FieldsDelegate(string s); 

protected int CreateComponent(
                               DbConnection cnctn, 
                               string tableName, 
                               Dictionary<string, object> changedFieldValues,
                               Func<string, bool> fieldsDelegate
                             )

关于c# - 如何在 C#/.NET 4.0 中编写带有委托(delegate)参数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5802009/

相关文章:

c# - 如何将数据行流式传输到sql server?

c# - 升级 ASP.NET MVC 2 项目后,如何在 System.Web.dll 中查找 StackOverflowException 的原因?

c# - 查询附加实体

c# - 有没有办法将 System.IO.Stream 转换为 Windows.Storage.Streams.IRandomAccessStream?

c# - 方法内的临时方法?

c# - 赋予委托(delegate)属性的优雅方式

c# - 何时在 C# 中使用 get 和 set 属性

C# HttpClient POST 请求

c# - 通过服务或直接访问存储库?

c# - 使用带有预定义委托(delegate)签名的 async/await