2017-04-25 35 views
1

如果这个问题出现“基本”,但是我没有对代表做很多事情,并且我正在努力克服正确的语法 - 如果这是可能的话。可重复使用的代表

我用这样的委托:

Func<KeyValuePair<string, PostMeta>, bool> filter = x => 
x.Value.Category == pageMeta.Value.Category && x.Key != pageMeta.Key; 

然而,我发现自己一次又一次地重新使用这个笨拙的一部分Func<KeyValuePair<string, PostMeta>, bool> - 感觉它应该像一个属性的getter/setter,但我不确定。

下面是一些非工作的代码来进一步证明:

宣言

delegate void PostFilter<Func<KeyValuePair<string, PostMeta>, bool>>(); 

用法:

PostFilter = x => x.Value.Category == pageMeta.Value.Category && x.Key != pageMeta.Key; 

任何意见赞赏。

回答

1

如果要定义它接受KeyValuePair<string, PostMeta>类型的一个参数,并返回bool(作为你的第一个代码片段暗示)的委托类型,使用此声明:

delegate bool PostFilterDelegate(KeyValuePair<string, PostMeta> param); 

然后你可以使用的变量PostFilterDelegate类型:

不是定义委托
PostFilterDelegate PostFilter = x => 
    x.Value.Category == pageMeta.Value.Category && x.Key != pageMeta.Key; 
+0

感谢您的快速回答。不幸的是,这个答案改变了Func 的签名,所以我不能再将这个一般地传递​​给其他方法而无需修改或接口。 –

1

其他,多一个选择是使用using指令创建类型别名。以下是几个示例:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

using EqualsFunc = System.Func<int, int, bool>; 
using PostFilter = Func<System.Collections.Generic.KeyValuePair<string, PostMeta>, bool>; 
using MyPair = System.Collections.Generic.KeyValuePair<string,int>; 

namespace TypeAlias 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      EqualsFunc equals = (a, b) => a == b; 
      var result == equals(1, 2); //false 

      PostFilter filter = x => 
      x.Value.Category == pageMeta.Value.Category && x.Key != pageMeta.Key; 
      var filterResult = filter(new MyPair("key",5),10); 
     } 
    } 
}