我希望你能帮我翻译一下这段关于C#语法的内容。这里我想将一个任意委托分配给一个类。
我的委托定义如下:
delegate string stringCB(string s);
delegate int intCB(int i);
我有一个类
class run_by_name {
public string name {get;set;}
public Delegate method {get;set;}
};
我正在尝试实例化它
run_by_name myfuc = new run_by_name(){
name = "my name",
method = new stringCB(string s) {
return " testing " + s;
};
};
我真的不清楚在有返回类型时如何分配代理。而且,我不确定语法上如何稍后调用该方法。
为什么这样做?好吧,我只是编写了一些代码,遵循我经常在事件处理中使用的模式,我只是创建了一个“对象”,可以将任意函数分配给它,用于定义而非创建的通用事件处理程序。(重要)
此外,欢迎使用代理的替代方案:)
编辑:我可能如何稍后使用它
我还没有写过,但我相当确定我会这样做。
List<run_by_name> callbacks = new List<run_by_name>();
/* lets say this is initialized and filled at this point */
public object FindAndRunCallback(string Name, object input) {
foreach(var cb in callbacks) {
if( cb.name == Name )
return cb.method(input);
}
return null;
}
Action<T>
和Func<T>
及其相关类。 - Daniel A. WhiteFunc
。 - rageitmethod = (string s) => (" testing " + s);
,而不是method = new stringCB(string s) { return " testing " + s; };
。 - Jashaszun