问题
I currently have something that I want to pass a textbox.text by ref. I don't want to pass the whole textbox and I want the function to change the text along with returning the other variable.
public int function(int a, int b, string text)
{
//do something
if (a + b > 50)
{
text = "Omg its bigger than 50!";
}
return (a + b);
}
Is there a way to pass the Textbox.text by ref and change it inside the function?
回答1:
You can't pass a property by ref, only a field or a variable.
From MSDN :
Properties are not variables. They are actually methods, and therefore cannot be passed as ref parameters.
You have to use an intermediate variable :
string tmp = textBox.Text;
int x = function(1, 2, ref tmp);
textBox.Text = tmp;
回答2:
What do you mean pass the "whole" textbox? If your signiture is public int function(int a, int b, TextBox textBox)
then all you are passing is a reference, which is not much data at all. If you make your signature public int function(int a, int b, ref string text)
, you still have a problem if passing textBox.Text because you'll still be working with a copy of the backing field from the Text property so your method won't update.
回答3:
Why don't you want to pass the whole textbox? it's pass in ref... like:
public int function(int a, int b, TextBox textb)
{
//do something
if (a + b > 50)
{
textb.text = "Omg its bigger than 50!";
}
return (a + b);
}
回答4:
You cannot pass a property by ref. You can copy the .Text
property to a string and then pass that string by ref:
void foo()
{
string temp = MyTextBox.Text;
int result = refFunction(ref temp);
MyTextBox.Text = temp;
}
int refFunction(ref string text)
{ ... }
回答5:
I assume the problem is that you're trying to pass TextBox.Text
to the second parameter of your function (assuming that you have modified it to take the string by reference). It is perfectly valid to pass strings by reference, however properties cannot be passed by reference. The best that you can do is assign the text to another string, pass that, then set the text back into the TextBox afterwards:
public int function(int a, int b, ref string text)
{
//do something
if (a + b > 50)
{
text = "Omg its bigger than 50!";
}
return (a + b);
}
string text = TextBox.Text;
function(ref text);
TextBox.Text = text;
来源:https://stackoverflow.com/questions/2028763/pass-by-ref-textbox-text