Domanda

I ran into this code:

bool success = true;
Thread connectThread = new Thread(delegate() { success = TryConnectingToAnalysisServer(connectionString); });

I never saw this syntax for a delegate, can somebody explain it?

È stato utile?

Soluzione

It's an anonymous delegate. Instead of having to write a separate function, which is what you had to in C# version 1.0:

void MainMethod()
{
    bool success = true;
    Thread connectThread = new Thread(new ThreadStart(thread_start));
}
void thread_start() {
    success = TryConnectingToAnalysisServer(connectionString); 
}

With C# 2.0 you can now write this more compactly with a anonymous method:

void MainMethod()
{
    bool success = true;
    Thread connectThread = new Thread(delegate() {
        success = TryConnectingToAnalysisServer(connectionString); 
    });
}

With C# 3.0 you can write this slightly more compactly using a lambda expression:

void MainMethod()
{
    bool success = true;
    Thread connectThread = new Thread(() => {
        success = TryConnectingToAnalysisServer(connectionString); 
    });
}

Altri suggerimenti

Its called Annonymous Methods. What happeneds is the compiler generates a named method for you behind the scenes with the correct signature of the delegate. So the compiler generates a method:

public void <__k_method()
{
   success = TryConnectingToAnalysisServer(connectionString)
}

I suggest you read up, and also look into Lambda Expressions

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top