Given the following MSDN sample code, why can't I define the Action delegate "inline":
public static void Main(string[] args)
{
Action someAction = () => Console.WriteLine("Hello from the thread pool!");
Task.Factory.StartNew(someAction);
}
...so "inline" like:
public static void开发者_StackOverflow社区 Main(string[] args)
{
Task.Factory.StartNew(Action someAction = () => Console.WriteLine("etc."));
}
Thanks,
Scott
This isn't valid C#:
public static void Main(string[] args)
{
Task.Factory.StartNew(Action someAction = () => Console.WriteLine("etc."));
}
Do this instead:
public static void Main(string[] args)
{
Task.Factory.StartNew(() => Console.WriteLine("etc."));
}
You're trying to delegate a variable within a method call. Just removing the variable declaration may be fine:
public static void Main(string[] args)
{
Task.Factory.StartNew(() => Console.WriteLine("etc."));
}
Here the Action
is inferred not from the lambda expression itself, but from the method call it's trying to make. Normal overload resolution is performed, and the compiler tries to convert the lambda expression to the relevant parameter type. If the parameter type were just Delegate
(e.g. Control.Invoke
) then type inference would fail because the compiler wouldn't have any concrete target types to try to convert to.
If that doesn't work (I can't easily test it atm) then you just need a cast to tell it which delegate type the lambda expression should be converted to:
public static void Main(string[] args)
{
Task.Factory.StartNew((Action)(() => Console.WriteLine("etc.")));
}
To be honest though, at that point I'd prefer to see a separate variable in terms of readability.
You are including the declaration statement, which is not a legal expression. Try:
Task.Factory.StartNew(() => Console.WriteLine("etc."));
If you call an API where the type of the delegate can't be inferred, you can use a cast or call the delegate constructor explicitly:
Task.Factory.StartNew((Action)(() => Console.WriteLine("etc.")));
Task.Factory.StartNew(new Action(() => Console.WriteLine("etc.")));
I wouldn't know tbh, but I think you can do:
public static void Main(string[] args)
{
Task.Factory.StartNew(delegate() {Console.WriteLine("etc.");});
}
精彩评论