我一直在使用我在类级别声明委托(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 现在提供 Action和 Func用于此目的的泛型。
在您的情况下,此委托(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/