问题
I'm trying to make an integer which consists of numbers that are in box1 (in wpf). but the compiler won't allow me to compile my code. what's wrong?
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private int addValues()
{
int var1 = int.Parse(box1.Text);
}
}
error is:
wpfapplication1.mainwindow.addValues. not all code paths return a value
回答1:
private int addValues()
{
int var1 = int.Parse(box1.Text);
return var1;
}
Its non-sensible, having a method with a return type but not returns a value.
Make Sensible as,
private void addValues()
{
int var1 = int.Parse(box1.Text);
}
回答2:
You need to return something in your AddValues (int value) or set it to void.
So for example:
private int addValues(){ return int.Parse(box1.Text); }
or
private void addValues(){ int var1 = int.Parse(box1.Text); }
The problem with the last method (your method) does nothing at all (parses a value and does not use it anywhere).
回答3:
Since you have declared the return type of your addValues
method as an int
you are telling the compiler you expect this method to return a value, therefore at some point your method must return an integer for example
private int addValues()
{
return int.Parse(box1.Text);
}
Other options include removing the return type
private void addValues()
{
int var1 = int.Parse(box1.Text);
}
Minor Note would be to use TryParse
to add error handling - This will ensure that if box1.Text
isn't a valid number, you will still return an integer (0)
private int addValues()
{
int ret_val;
int.TryParse(box1.Text, out ret_val);
return ret_val;
}
来源:https://stackoverflow.com/questions/25075123/cant-use-textbox-outside-mainwindow-method