委托作为c#类构造函数的参数
本文关键字:构造函数 参数 | 更新日期: 2023-09-27 18:11:25
嗨,我有一个类的委托作为参数,如代码中所示,但我得到的错误Error 1 Type expected ...'Classes'Class1.cs 218 33 Classes
和Error 2 ; expected ...'Classes'Class1.cs 218 96 Classes
。我如何解决这个问题?提前感谢!我试图通过ref传递它当一个类初始化时,它的一些方法被附加到委托上。
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