[英]How do I get rid of the error message "cannot implicitly type CLASSLibrary(classname) to ClassLibrary.(classname)
[英]How do I get rid of this error message in my function?
我在一个类中有一个函数,但是在“提现”下收到错误,“并非所有代码路径都返回一个值”。 我以为添加空隙可以解决问题,但似乎无法消除它。 知道如何修改代码吗? 这是一部分:
public virtual double Withdraw(double amount)
{
if (amount > balance)
{
MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
return balance - amount;
}
由于您已声明函数返回double
,因此无论if
采用if
,都需要执行该操作。
在MessageBox
返回之后,您需要从if
的true
面返回一个值,例如:
if (amount > balance)
{
MessageBox.Show(...);
return balance;
}
else ...
这不是一个直接的答案,但我认为您的Method有许多用途,可以进行计算并向用户显示一条消息,您应该考虑使用这样的两种方法
public virtual double Withdraw(double amount)
{
if (amount > balance)
throw new Exception("your message")
else
return balance - amount;
}
呼叫者的代码
try{
Withraw(...)
}
catch{
Your messageBox
}
您的ode在任何情况下都应始终返回一些值,因此
public virtual double Withdraw(double amount)
{
if (amount > balance)
{
MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return SOME_NON_VALID_VALUE_FOR_YOUR_APP; //or raise an exception,
// depends on architecture
}
return balance - amount;
}
考虑提供的代码的逻辑,如果amount > balance
不正确,否则返回计算。
您下面的代码行未返回任何值是主要的根本原因:
if (amount > balance)
{
MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
您应该在MessageBox.Show
之后返回一个双MessageBox.Show
值。
您需要在MessageBox.Show
之后撤消某些操作。显示理想状态0
public virtual double Withdraw(double amount)
{
if (amount > balance)
{
MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return 0;
}
else
return balance - amount;
}
您的函数应该返回一个双精度值,但是如果amount>balance
则不会。
public virtual double Withdraw(double amount)
{
if (amount > balance)
{
//your messagebox code
return double.NaN; // or whatever you think is correct in this case.
}
else
return balance - amount;
}
您正在通过函数返回double
值。
但仅在其他部分中提及。
如果,if(金额>余额)条件为true,则还必须返回该值。
请参阅以下代码:
public virtual double Withdraw(double amount)
{
if (amount > balance)
{
MessageBox.Show("Debit amount exceeded account balance.", "Insufficient funds!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
return balance - amount;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.