2012-09-26 32 views
0

我目前正在尝试使用(可能)使用C#的Func或Action类型的lambdas。将函数作为接口方法定义中的参数传递

我想创建一个名为IMyInterface的接口,它定义了一个名为CreateCRUD的方法。这应该需要5个参数。首先是一个字符串。接下来的四个是调用创建,读取,更新和删除方法的函数。

interface IMyInterface 
{ 
    void CreateCRUD(string name, Action<void> createFunc, Action<void> readFunc, Action<void> updateFunc, Action<void> deleteFunc); 
} 

这四个函数定义应该不带任何参数,不返回任何内容。上面的代码不能编译。请指向正确的方向。

回答

4

改为使用非通用Action

interface IMyInterface 
{ 
    void CreateCRUD(string name, Action createFunc, Action readFunc, Action updateFunc, Action deleteFunc); 
} 
+2

“无效不是一个类型”:这并不完全正确...'typeof运算(无效)''返回System.Void'。但它不能用作泛型类型参数 –

+0

呵。不知道。编辑我的答案,今天学到了新的东西。感谢:) –

1

Action<T>

封装,其具有单个参数,并且不返回 一个值的方法。

因此,您试图强制使用void类型的一个参数的委托。

所有你需要做的是使用Action无类型:

interface IMyInterface 
{ 
    void CreateCRUD(string name, Action createFunc, Action readFunc, Action updateFunc, Action deleteFunc); 
} 

如果要强制参数类型的代表,那么你可以应该使用Action<T>例如Action<int>,其中表示方法与int参数。

+0

所以,Func和Action的唯一区别是返回类型?行动没有,Func呢? –

+0

@Norla - 确切地说。 –

0

喜欢的东西

Public delegate Action<T> MyActionDelegate; 

interface IMyInterface 
{  
void CreateCRUD(string name, MyActionDelegate createFunc, MyActionDelegate readFunc, MyActionDelegate updateFunc, MyActionDelegate deleteFunc); 
} 
+0

问:创建委托与下面的答案有什么不同? –

+0

它没有。但是,如果没有定义合适的委托,则可以定义一个委托,然后将其用作方法中的一个类型。 –

+0

为每个CRUD操作创建4个代表是否合适? –

相关问题