[英]Delegate as parameter in C# class constructor
嗨我有一个代理作为参数的类,如代码所示,但我得到错误Error 1 Type expected ...\\Classes\\Class1.cs 218 33 Classes
和Error 2 ; expected ...\\Classes\\Class1.cs 218 96 Classes
Error 2 ; expected ...\\Classes\\Class1.cs 218 96 Classes
。 我该如何解决这个问题? 提前致谢! 我试图传递它byref所以当一个类初始化时,它的一些方法被附加到委托。
public constructor(ref delegate bool delegatename(someparameters))
{
some code
}
您不能在构造函数中声明委托类型。 您需要首先声明委托类型,然后您可以在构造函数中使用它:
public delegate bool delegatename(someparameters);
public constructor(ref delegatename mydelegate)
{
some code...
}
您可以传递类似Action<T>
...但不确定为什么要通过引用传递它。 例如,您可以使用以下方法:
static void Foo(int x, Action<int> f) {
f(x + 23);
}
并称之为:
int x = 7;
Foo(x, p => { Console.WriteLine(p); } );
1 - 为什么要使用ref
关键字?
2 - constructor
是类名吗? 如果没有,你做错了,不同的PHP: public function __construct( .. ) { }
构造函数被命名为类名,例如:
class foo {
public foo() { } // <- class constructor
}
3 - 通常代表的类型无效。
你在找这个吗?
class Foo {
public delegate bool del(string foo);
public Foo(del func) { //class constructor
int i = 0;
while(i != 10) {
func(i.ToString());
i++;
}
}
}
然后:
class App
{
static void Main(string[] args)
{
Foo foo = new Foo(delegate(string n) {
Console.WriteLine(n);
return true; //this is it unnecessary, you can use the `void` type instead. });
Console.ReadLine();
}
}
输出:
1
2
3
4
5
6
7
8
9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.