C#委托代码报错:预期输出‘1’却出现错误求助
Let's walk through the issues in your code that are causing errors and stopping you from getting the expected "1" output—there are two key problems here:
1. You're trying to output a void method's "return value"
Your ShowDelegate method is declared as void, meaning it doesn't return anything. But in Main, you're calling Console.WriteLine(fclass.ShowDelegate(show))—this will throw a compile error because you can't pass a void result to a method that expects a string (or any value at all).
2. The delegate's return value is being discarded
Inside ShowDelegate, you call SD(1), which correctly returns the string "1"—but you don't do anything with that value. It just gets lost after the delegate runs.
Here are two working fixes depending on what you want ShowDelegate to do:
Fix 1: Make ShowDelegate return the delegate's result
This lets the caller handle the output (or any other processing):
public class FClass { public delegate string Show(int n); // Change return type from void to string public string ShowDelegate(Show SD) { return SD(1); // Return the delegate's output } } public class SClass { static string ReturnString(int n) { return n.ToString(); } static void Main(string[] args) { FClass fclass = new FClass(); FClass.Show show = new FClass.Show(ReturnString); // Now this works because ShowDelegate returns a string Console.WriteLine(fclass.ShowDelegate(show)); } }
Fix 2: Have ShowDelegate handle the output directly
If you want ShowDelegate to be responsible for printing the result:
public class FClass { public delegate string Show(int n); public void ShowDelegate(Show SD) { string result = SD(1); Console.WriteLine(result); // Print the result here } } public class SClass { static string ReturnString(int n) { return n.ToString(); } static void Main(string[] args) { FClass fclass = new FClass(); FClass.Show show = new FClass.Show(ReturnString); // Just call the method—no need for Console.WriteLine here fclass.ShowDelegate(show); } }
Either fix will give you the expected output of "1" when you run the code.
内容的提问来源于stack exchange,提问作者syryl

