2011-04-27 73 views
6

我一直在使用,我在課堂上一級聲明委託的方式:如何用C#/ .NET 4.0中的委託參數編寫方法?

protected delegate void FieldsDelegate(); 

//and then write a method e.g. 

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

然而這實在是很麻煩,我不能立即看到該委託是什麼樣的。所以我想這樣做:

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

這樣我就沒有單獨的定義。

由於某種原因,以上情況是不允許的。那我該怎麼做呢?

+0

其實後綴'Delegate'在'FieldsDelegate'已經是一個很好的指標。如果你不同意 – 2011-04-27 09:44:11

回答

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 
          ) 

如果一個字符串作爲一個參數:

// protected delegate void FieldsDelegate(string s); 

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

如果一個字符串作爲參數,並返回一個布爾值:

// protected delegate bool FieldsDelegate(string s); 

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

回滾 – 2011-04-27 09:40:24

+0

@亨克 - 我同意。如果我包含它所替換的委託,則更容易理解。 – 2011-04-27 09:52:40

5

你可以使用通用Action<T>Func<T>及其變體作爲代表,並且獎金是你甚至不需要定義一個單獨的委託。

Action<T>最多需要16個不同的類型參數,所以:Action<T1, T2>和on;每個類型參數都是該方法在相同位置的類型參數。所以,Action<int, string>將這種方法工作:

public void MyMethod(int number, string info) 

Func<T>是一樣的,只不過它是返回一個值的方法。最後一個類型參數是返回類型。 Func<T>不是你在這裏使用的案例。

例如:Func<string, int, object>將是一個方法,如:

public object MyOtherMethod(string message, int number) 

使用這些通用的代表清楚地爲代表論點的論據是什麼,這似乎是你的意圖。

public void MyMethod(Action<string, MyClass>, string message) 

調用該方法時,你知道你需要傳遞一個方法,需要一個stringMyClass

public void MeOtherMethod(Func<int, MyOtherClass>, int iterations) 

在這裏,你知道你需要傳遞需要一個int參數的方法,並返回MyOtherClass