C# 当需要在调用时访问其参数时,如何使用Func?

C# 当需要在调用时访问其参数时,如何使用Func?,c#,function,delegates,C#,Function,Delegates,我有一个字典,其中包含一个字符串作为键,还有一个在发现该字符串时运行的函数。然后,它传入被发现的所使用的对象。我只想访问函数体中的这个对象,但不确定如何操作。我认为必须使用lambda操作符,但我真的不知道如何正确使用它 公共字典stringReceivedRegister; 我的设置 string-received\u-name=StringFormatter.GetName(receivedMessage); objectchanged_string=openMethod.Invoke(实

我有一个字典,其中包含一个字符串作为键,还有一个在发现该字符串时运行的函数。然后,它传入被发现的所使用的对象。我只想访问函数体中的这个对象,但不确定如何操作。我认为必须使用lambda操作符,但我真的不知道如何正确使用它

公共字典stringReceivedRegister;
我的设置

string-received\u-name=StringFormatter.GetName(receivedMessage);
objectchanged_string=openMethod.Invoke(实例,新对象[]{receivedMessage});
StringTypes.Instance.stringReceivedRegister[收到的\u名称].Invoke(已更改的\u字符串);
将函数添加到stringReceivedRegister时,如何在传入的函数中访问它

StringTypes.Instance.stringReceivedRegister.Add(“Test”,可以访问“已更改字符串”的函数);
看看这个代码:

static bool FunctionTest(object o) {
return true;
}
static void Main(string[] args) {
Dictionary<string, Func<object, bool>> dict = new Dictonary<string, Func<object, bool>>();
dict.Add("A", ((obj) => { return false; }));
dict.Add("B", FunctionTest);

Console.WriteLine(dict["A"](1));
Console.WriteLine(dict["B"](1));
静态布尔函数测试(对象o){
返回true;
}
静态void Main(字符串[]参数){
Dictionary dict=新的dictional();
dict.Add(“A”,((obj)=>{return false;}));
添加(“B”,功能测试);
控制台写入线(dict[“A”](1));
控制台写入线(dict[“B”](1));

要将函数添加到
stringReceivedRegister
,首先需要声明一个方法:

private static bool MyFunction(object x) {
    // ...
}
然后您可以将
MyFunction
传递到
Add

// Note the absence of () after "MyFunction". I am not actually calling it
stringReceivedRegister.Add("Test", MyFunction);
执行此操作时,
x
参数将引用
changed\u字符串

StringTypes.Instance.stringReceivedRegister[received_name].Invoke(changed_string);

每次都要声明一个方法是非常烦人的,因此C#3提供了lambda表达式,允许您执行以下操作:

stringReceivedRegister.Add("Test", x => {
    // ...
});

同样地,
x
在使用
changed\u string
调用委托时,将引用
changed\u string

不太确定您得到的是什么,但是……假设您有一个带有签名的函数
bool Foo(对象输入)
,那么它就简单到
。添加(“Test”,Foo)
如果你不确定,那你怎么回答这个问题?@DavidG-如果他想知道如何将函数存储为字典中的值,那么我就发布了正确的方法。在99%的情况下,这是他的puproseOK,因此你删除了“我不确定”文本,这很好,但现在你只需说“看看这段代码”,这是一段多余的文字。所以现在你有了一个答案,这是一个没有解释的代码转储。作为信息,这不是我的反对票,我只是想帮助你写出更好的答案。