【发布时间】:2015-04-02 10:18:24
【问题描述】:
我正在寻找一种在 C# 中实现访问者的紧凑方法。 该代码将用于 Unity3D 中的“object hierarchy walker”功能。
主要问题是我不知道如何在 C# 中将“通用可调用参数”声明为方法参数。
static void visitorTest(var visitor){ // <<---- which type?
int i = 0;
visitor(i);
}
可以很容易地用C++模板函数表达
template<class Visitor> void visitorTest(Visitor visitor){
visitor(i);
}
理想情况下vistior 应该接受类、方法(或静态方法)和某种“lambda”表达式。接受“类”是可选的。
我确实尝试使用来自 here 和 here 的信息用 C# 编写它,但我没有做对。
我缺少一些基本知识,主要与委托、Action、方法和 Func 之间的转换有关,如果有人指出我还不知道的确切内容或者只是向我举个例子,这样我就可以自己弄清楚了(修复两个编译错误会比解释所有内容花费更少的时间)。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTest
{
class Program
{
public delegate void Visitor(int i);
public void visitorTest(Visitor visitor){
int[] tmp = new int[10];
for (int i = 0; i < tmp.Length; i++){
tmp[i] = i;
}
foreach(var i in tmp){
visitor(i);
}
}
public static void funcCallback(int arg) {
System.Console.WriteLine("func: " + arg.ToString());
}
static void Main(string[] args)
{
//An object reference is required for the non-static field, method, or property 'ConsoleTest.Program.visitorTest(ConsoleTest.Program.Visitor)
visitorTest(new Visitor(funcCallback));
int mul = 2;
Action< int> lambda = (i) => System.Console.WriteLine("lambda: " + (2*i).ToString());
//The best overloaded method match for 'ConsoleTest.Program.visitorTest(ConsoleTest.Program.Visitor)' has some invalid arguments
//Argument 1: cannot convert from 'System.Action<int>' to 'ConsoleTest.Program.Visitor'
visitorTest(lambda);
}
}
}
C++ 代码示例:
理想情况下,我希望拥有与此代码片段 (C++) 等效的代码:
#include <vector>
#include <iostream>
template<class Visitor> void visitorTest(Visitor visitor){
//initialization, irrelevant:
std::vector<int> tmp(10);
int i = 0;
for(auto& val: tmp){
val =i;
i++;
}
//processing:
for(auto& val: tmp)
visitor(val);
}
//function visitor
void funcVisitor(int val){
std::cout << "func: " << val << std::endl;
}
//class visitor
class ClassVisitor{
public:
void operator()(int arg){
std::cout << "class: " << arg*val << std::endl;
}
ClassVisitor(int v)
:val{v}{
}
protected:
int val;
};
int main(){
visitorTest(funcVisitor);
visitorTest(ClassVisitor(2));
int arg = 3;
/*
* lambda visitor: equivalent to
*
* void fun(int x){
* }
*/
visitorTest([=](int x){ std::cout << "lambda: " << arg*x << std::endl;});
}
输出:
func: 0
func: 1
func: 2
func: 3
func: 4
func: 5
func: 6
func: 7
func: 8
func: 9
class: 0
class: 2
class: 4
class: 6
class: 8
class: 10
class: 12
class: 14
class: 16
class: 18
lambda: 0
lambda: 3
lambda: 6
lambda: 9
lambda: 12
lambda: 15
lambda: 18
lambda: 21
lambda: 24
lambda: 27
visitorTest 是一个通用(模板)函数,可以将 lambda 表达式、类或函数作为回调。
funcTest 是函数回调。
classTest 是一个类回调。
main() 中的最后一行有 lambda 回调。
我可以通过提供各种抽象基础来轻松地创建基于类的回调,但我希望有更灵活的方法,因为编写完整的类通常过于冗长,而为这种简单的事情编写抽象基础是多余的。
在线信息表明这样做的方法是使用 Linq 和 Delegates,但我无法在它们之间转换或只是传递委托。
建议?
【问题讨论】:
标签: c# c++ linq lambda delegates