并非所有代码路径都返回一个值,任何一个请提供解决方案 [英] not all code paths return a value can any one please provide a solution
本文介绍了并非所有代码路径都返回一个值,任何一个请提供解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class ProductModel
{
public string InsertProduct(Product product)
{
try
{
GarageEntities db = new GarageEntities();
db.Products.Add(product);
db.SaveChanges();
return product.Name + "was succesfully inserted";
}
catch (Exception e)
{
return "Error:" + e;
}
}
推荐答案
编译器抱怨函数末尾缺少return语句(他是不够聪明,无法检测到从未到达终点)。您有三种选择:
- 忽略或取消警告(非专业)。
- 最后返回结果(将返回点从try块移到结尾处。)
- 最后返回一些内容。
The compiler complains about a missing return statement at the end of the function (he is not smart enough to detect that the end is never reached). You have three options:
- Ignore or suppress the warning (nonprofessional).
- Return the result at the end (move the return from the try block to the end).
- Return something at the end.
public string InsertProduct(Product product)
{
try
{
GarageEntities db = new GarageEntities();
db.Products.Add(product);
db.SaveChanges();
// May be moved to end of function
return product.Name + "was succesfully inserted";
}
catch (Exception e)
{
return "Error:" + e;
}
// Make the compiler happy or return success here
return "";
}
询问此类问题的提示:
始终包含编译器代码(此处为CS0161),因为这样可以清楚地说明发生了什么。但是,在网上搜索消息和/或代码也会回答这个问题。
A tip for asking about such problems:
Always include the compiler code (CS0161 here) because this makes it clear what happened. However, searching the web for the message and/or code would have answered this too.
这篇关于并非所有代码路径都返回一个值,任何一个请提供解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文