Hi i have a class with a delegate as a parameter as shown in the code, but i get the errors Error 1 Type expected ...\\Classes\\Class1.cs 218 33 Classes
and Error 2 ; expected ...\\Classes\\Class1.cs 218 96 Classes
Error 2 ; expected ...\\Classes\\Class1.cs 218 96 Classes
. How do i fix the issue? Thanks in advance! I'm trying to pass it byref so when a class initializes, some method of it is attached to the delegate.
public constructor(ref delegate bool delegatename(someparameters))
{
some code
}
You cannot declare the delegate type in the constructor. You need to first declare the delegate type, and then you can use it in the constructor:
public delegate bool delegatename(someparameters);
public constructor(ref delegatename mydelegate)
{
some code...
}
You can pass something like Action<T>
... not sure why you want to pass it by reference though. For example, you can have a method like this one:
static void Foo(int x, Action<int> f) {
f(x + 23);
}
And call it like this:
int x = 7;
Foo(x, p => { Console.WriteLine(p); } );
1 - Why you're using the ref
keyword?
2 - the constructor
is the class name? if not, you're doing this wrong, different of PHP: public function __construct( .. ) { }
the constructor is named of class name, for example:
class foo {
public foo() { } // <- class constructor
}
3 - Normally the types of delegates are void.
You're looking for this?
class Foo {
public delegate bool del(string foo);
public Foo(del func) { //class constructor
int i = 0;
while(i != 10) {
func(i.ToString());
i++;
}
}
}
Then:
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();
}
}
The output:
1
2
3
4
5
6
7
8
9
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.