【发布时间】:2011-10-11 21:18:03
【问题描述】:
我是 c# 的新手,这是我正在从事的个人项目的摘录,以获取一些经验。
当在这个类之外调用getRecipe() 函数时,出现以下错误。我想让我的List 对CookBook 类保持私有,但仍然能够在List 中获得对Recipes 之一的引用。我不想公开我的List。
非常感谢任何建议!谢谢
错误
return type 'cookbook.Recipe is less accessible than method 'cookbook.CookBook.getRecipe(string)'
public class CookBook
{
private List<Recipe> listOfRecipes = new List<Recipe> {};
public Recipe getRecipe(string name)
{
int i = 0;
while (listOfRecipes[i].getRecipeName() != name)
{
i++;
}
return listOfRecipes[i];
}
}
【问题讨论】:
-
只是一些建议:您可以使用 LINQ 使代码更简洁:
return listOfRecipes.FirstOrDefault(recipe => recipe.getRecipeName().Equals(name,StringComparison.InvariantCultureIgnoreCase));。如果请求一个不存在的配方,您当前的代码将失败(它会抛出一个 IndexOutOfRangeException),它还会进行区分大小写的比较(因此“蛋糕”将找不到“蛋糕”)。最后的建议是,不要使用 getRecipeName 或 getRecipe 之类的名称。使用 PascalCase (GetRecipe),并考虑属性/索引器(CookBook["Cake"] 或 CookBoox.Recipes["Cake"],Recipe.Name)。 -
感谢您的建议,我现在正在研究 LINQ。
-
您发布的 linq 语句中的“=>”是什么意思?
-
这是一个 lambda 函数。我基本上是在声明一个函数(所谓的“谓词”)
private bool DoesRecipeMatch(Recipe recipe, string name){ return recipe.getRecipeName().Equals(name,StringComparison...); },然后 LINQ 语句执行foreach(Recipe recipe in listOfRecipes) { if(DoesRecipeMatch(recipe,name)) { return recipe; } return default(Recipe); }。换句话说,它或多或少地完成了您所做的事情(除了迭代中的错误),但它更简洁并专注于您的意图(查找名称匹配的配方)而不是单个步骤(迭代、比较、返回) -
另见 Joseph Daigle 对此问题的回答:stackoverflow.com/questions/167343