我传递一个stringbuild out变量来执行哪个参数类型是stringbuild,但编译器打电话给我
"在离开功能之前,您必须为sbValue"
指定值 public void FuncOutParamString(out StringBuilder sbValue)
{
sbValue.Append("wold!");
}
private void btnOutParam_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("=================== Out Parameter ===================");
// Declare a variable but don't assign a value to it ******************************
int y = 0;
// Pass it in as an output parameter, even though its value is unassigned
FuncOutParamInt(out y);
// It's now assigned a value, so we can write it out:
Console.WriteLine(y);
// Declare a variable but don't assign a value to it ******************************
StringBuilder sb = new StringBuilder();
sb.Append("Hello ");
FuncOutParamString(out sb);
Console.WriteLine(sb);
}
抱歉,发布图片需要10点声望
答案 0 :(得分:1)
[out]表示要创建。 [class]是参考类型。
public void FuncOutParamString(StringBuilder sbValue)
{
sbValue.Append("wold!");
}
public void FuncOutParamStringRef(ref StringBuilder sbValue)
{
//if(...)
sbValue = new StringBuilder();
}
public void FuncOutParamStringOut(out StringBuilder sbValue)
{
sbValue = new StringBuilder();
}
答案 1 :(得分:0)
当将变量sb声明为StringBuilder时,必须将值传递给构造函数,否则它将初始化为null。由于它需要从堆中分配内存,因此需要一个参数以便稍后使用。
您可以检查here以获取StringBuilder类支持的构造函数参数的类型。
这应该有效:
public void FuncOutParamString(StringBuilder sbValue)
{
sbValue.Append("wold!");
return sbValue;
}
private void btnOutParam_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("=================== Out Parameter ===================");
// Declare a variable but don't assign a value to it ******************************
int y = 0;
// Pass it in as an output parameter, even though its value is unassigned
FuncOutParamInt(out y);
// It's now assigned a value, so we can write it out:
Console.WriteLine(y);
// Declare a variable but don't assign a value to it ******************************
StringBuilder sb = new StringBuilder(50);
sb.Append("Hello ");
sb = FuncOutParamString(sb);
Console.WriteLine(sb);
}
此外,您必须从FuncOutParamString函数返回sbValue变量。