[英]How do you properly return `null` from a generic marked with [return:MaybeNull]?
[英]How do you return a value properly?
我正在开发一个允许用户跟踪省钱目标的应用程序。
public static int CalcProg(int userGoal, int userBalance, int userProg)
{
userProg = userBalance / userGoal;
userProg = userProg * 100
return userProg;
}
private void Form1_Load(object sender, EventArgs e)
{
//Calls the FileVerification Method
FileVerification();
//Sets the label1 transparency to true
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;
LoadData();
CalcProg(userGoal, userBalance, userProg);
progressBar1.Value = userProg;
progLabel = Convert.ToString(userProg);
label3.Text = progLabel;
}
这只是代码的一小部分,但这是我遇到问题的地方。
我使用方法读写变量userBalance和userGoal中使用的数据的文件。 一切都很好,因为当我在下面的转换函数中使用这些变量之一而不是“ userProg”时,它的显示效果与文本文件中的显示效果相同。
当我尝试进行转换时,我的问题来了。 我的公式在CalcProg中。 当我实际启动程序时,无论在文本文件中输入什么值,在变量userProg上设置其值的两个元素(进度条和标签)都将显示为零。
我已经尝试对CalcProg方法使用double并将userProg设置为double,但这是行不通的。 我有些困惑,如果有人可以帮助我,我将不胜感激。
实际的问题是,您正在从方法中返回一个int,但从未使用过它。 将您的代码更改为:
public static int CalcProg(int userGoal, int userBalance, int userProg)
{
userProg = userBalance / userGoal;
userProg = userProg * 100
return userProg;
}
private void Form1_Load(object sender, EventArgs e)
{
//Calls the FileVerification Method
FileVerification();
//Sets the label1 transparency to true
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;
LoadData();
progressBar1.Value = CalcProg(userGoal, userBalance, userProg);
progLabel = Convert.ToString(userProg);
label3.Text = progLabel;
}
如果您需要更改传递给方法的保存参数,并在调用该方法后使用该参数,则只需将参数更改为out
参数即可
您可以将方法称为
CalcProg(userGoal, userBalance, out userProg);
和方法
public static void CalcProg(int userGoal, int userBalance, out int userProg)
{
userProg = userBalance / userGoal;
userProg = userProg * 100;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.