【问题标题】:return type is less accessible than method返回类型比方法更难访问
【发布时间】:2011-10-11 21:18:03
【问题描述】:

我是 c# 的新手,这是我正在从事的个人项目的摘录,以获取一些经验。

当在这个类之外调用getRecipe() 函数时,出现以下错误。我想让我的ListCookBook 类保持私有,但仍然能够在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 =&gt; 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

标签: c# .net


【解决方案1】:

语法错误?

private List<Recipe> listOfRecipes = new List<Recipe> {};

应该是:

private List<Recipe> listOfRecipes = new List<Recipe>();

另外,你可以简单地使用 LINQ 来得到你的结果,我不在 VS 中,但是像这样......

public Recipe getRecipe(string name)
{
    return listOfRecipes.Where(c => c.RecipeName == name).SingleOrDefault();
}

【讨论】:

  • 我也是 - 我原以为乍一看不会编译 :)
  • 感谢 LINQ 的建议,现在正在研究。
【解决方案2】:

您的 Recipe 类比方法更难访问。您应该检查 Recipe 不是私有/内部的,并且您可以从该类范围之外看到 Recipe 类(快速修复将 Recipe 声明为公共类)。

正如 Michael Stum 在下面的评论中指出的那样,没有访问修饰符的类默认是内部的或私有的(如果它是嵌套类)。这可能是您的问题所在,您可能刚刚声明了 class Recipe 而不是 public class Recipe

【讨论】:

  • 只是添加,因为他是新的:任何没有修饰符的类都是内部我的默认值,除了私有的嵌套类(我认为)。
【解决方案3】:

正如错误消息明确指出的那样,Recipe 类比您的方法更难访问(例如,不是 public)。

【讨论】:

    【解决方案4】:

    公开Recipe 类。

    【讨论】:

    • 我忘了 c# 中的类默认是私有的...谢谢。
    • @prolink007:类默认为internal,而不是private。其实只有嵌套类可以private
    • 巴姆。简短而甜蜜。
    【解决方案5】:

    使方法内部化。希望它会起作用。

    【讨论】:

    • 欢迎来到 StackOverflow!如您所知,这个问题的答案大约在 5 年前就已经被接受了。如果您想为已经存在的答案添加更多详细信息,请尝试在您的答案中更具描述性。谢谢!
    【解决方案6】:

    让你的班级公开......没有那个你不能返回任何东西

    【讨论】:

      【解决方案7】:

      检查以确保“Recipe”类的可见性覆盖了您想要访问它的范围。

      【讨论】:

        【解决方案8】:

        在C#中,默认情况下,类是private,所以访问级别是有限的。 将您的模型类声明为公共(配方)public

        【讨论】:

          猜你喜欢
          • 2019-05-14
          • 2014-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-07
          • 2014-10-31
          相关资源
          最近更新 更多