2012-06-16 86 views
1

我有一个函数功能在我的代码,被声明是这样的:使用Func键<T>参数

Func<string, int, bool> Filter { get; set; } 

我怎样才能到达字符串和是函数功能的参数,以便在我的代码使用它们中的int变量?

+0

认为'过滤器'是一种方法。它没有'string'或'int'参数的值。这些值在调用方法时传递。 – alf

+0

Func没有字符串和int *变量*作为它的参数。它有字符串和int *值*。提供这些值的变量(可能是文字!)应该与Func无关。 – AakashM

回答

4

当函数被调用时,参数只有存在并且它们只在函数中可用。因此,例如:

foo.Filter = (text, length) => text.Length > length; 

bool longer = foo.Filter("yes this is long", 5); 

这里,值“是的,这是长”是text参数的值,而委托执行和同样价值5是length参数的价值,同时它的执行。在其他时候,这是一个毫无意义的概念。

你真的想达到什么目的?如果你能给我们更多的背景,我们几乎可以肯定地帮助你。

+0

我试图从用户那里得到一个函数,它应该过滤我在我的课堂上的一些元素。 每个元素由一个String和一个int组成,问题是我只有字符串部分,我想在调用这个函数的时候使用这个func来更新int部分。 我知道这不完全是正确的方式,但基于限制,我似乎是唯一的方法。 –

+0

@YoniPlotkin:对不起,我还不清楚发生了什么事。不应该依赖一个*接受* int的函数来更新它。如果你能提供一个简短但完整的例子来说明你想要达到的目标,那么可能会更清楚。 –

+0

对不起,我会尽力解释 我有一个组件,用户和服务器类 用户类看起来像那样'公共类组件{{; } int Status {get; } }' 和一些更多的功能... 用户类看起来像这样: 'public class User { string Id {get; } IDictionary Status {get; } IEnumerable RelevantComponents {get; } Func Filter {get;组; } } –

4

你可以使用匿名方法:

Filter = (string s, int i) => { 
    // use s and i here and return a boolean 
}; 

或标准的方法:

public bool Foo(string s, int i) 
{ 
    // use s and i here and return a boolean 
} 

,然后你可以在过滤器属性分配给此方法:

Filter = Foo; 
1

见这里的示例 - http://www.dotnetperls.com/func

using System; 

class Program 
{ 
    static void Main() 
    { 
    // 
    // Create a Func instance that has one parameter and one return value. 
    // ... Parameter is an integer, result value is a string. 
    // 
    Func<int, string> func1 = (x) => string.Format("string = {0}", x); 
    // 
    // Func instance with two parameters and one result. 
    // ... Receives bool and int, returns string. 
    // 
    Func<bool, int, string> func2 = (b, x) => 
     string.Format("string = {0} and {1}", b, x); 
    // 
    // Func instance that has no parameters and one result value. 
    // 
    Func<double> func3 =() => Math.PI/2; 

    // 
    // Call the Invoke instance method on the anonymous functions. 
    // 
    Console.WriteLine(func1.Invoke(5)); 
    Console.WriteLine(func2.Invoke(true, 10)); 
    Console.WriteLine(func3.Invoke()); 
    } 
} 
+6

你其实不需要调用Invoke,你只需要'func1(5)'。 – R0MANARMY