可访问性不一致:返回类型比方法C#更难访问

好的,所以这真的很奇怪。 我有一个私人成员,我想将它用于Form2。 我已经创建了一个公共静态方法,因此我可以将该成员转换为Form2。

这是我的代码:

private static AppController appController; private BreadRepository breadRep; private CakeRepository cakeRep; private SandwichRepository sandwichRep; public Form1() { InitializeComponent(); breadRep = new BreadRepository(); cakeRep = new CakeRepository(); sandwichRep = new SandwichRepository(); appController = new AppController(breadRep , sandwichRep, cakeRep); } public static AppController getController() { return appController; } 

我试图从Form1公开appController,但我得到更多的错误。 现在我明白了:

可访问性不一致:返回类型’exemplu_map.controller.AppController’比方法’exemplu_map.Form1.getController()’更难访问任何想法?

更新:

这是我的AppController类:

 class AppController { private BreadRepository breadRep; private SandwichRepository sandwichRep; private CakeRepository cakeRep; public AppController(BreadRepository breadRep, SandwichRepository sandwichRep, CakeRepository cakeRep) { this.breadRep = breadRep; this.sandwichRep = sandwichRep; this.cakeRep = cakeRep; } public void writeToFile(String file) { StreamWriter wr = new StreamWriter(file); String writeMe = ""; foreach(Bread e in breadRep.getAll()) { writeMe = writeMe + e.getAll() + "\n"; } foreach (Sandwich e in sandwichRep.getAll()) { writeMe = writeMe + e.getAll() + "\n"; } foreach (Cake e in cakeRep.getAll()) { writeMe = writeMe + e.getAll() + "\n"; } wr.Write(writeMe); wr.Close(); } } 

我已经将AppController更改为public,但我再次获得更多错误。 同样的错误,但对于breadRep,cakeRep,sandwichRep。

问题是,正如@ Selman22所解释的那样,你的方法是public ,而它的返回值是internal 。 (默认情况下,类是internal的。)

如果两者都是publicinternal ,一切都应该有效。

由于依赖于其他类,使类public似乎很困难。 而且,它可能不是最好的,因为默认情况下,最好不要让事情变得不那么容易。

使方法internal从另一端解决相同的问题。

无论如何,@ Selman22是第一个:)。 我刚加了两分钱,所以你应该接受他的答案:)。

可访问性由给予类型或成员的访问级别确定。 请务必注意,类型/类型成员的默认访问级别不同

类型的默认访问级别是内部的

成员的默认访问级别是私有的

同样重要的是要注意private不适用于类型(如果它是私有的,你如何构造一个类型 – 它只能构造自己),除非该类型嵌套在另一个类型中

知道了这一点,就很容易理解为什么在公开你的类型时会出错。 在使类型公开时,您打开程序集以供其他程序集引用,这意味着它们可以查看其中的类型。

如果您的类型被声明为public并且它们具有公共构造函数,那么期望它们的公共构造函数可以由外部程序集调用。 正因为如此,构成构造函数的所有类型或程序集中某个类型的任何其他公共成员都必须具有公共可访问性。

 public class SomeClass { // This class and this constructor are externally visible // The parameter of type SomeOtherClass must also be public in order // for external assemblies to be able to construct this type public SomeClass(SomeOtherClass someOtherClass) { } } // This would cause the issue you are having since this type is private but // is included within a public contract (above), therefore the accessibility is 'inconsistent' private class SomeOtherClass { } 

我离题了 – 你的问题是成员可访问性

您的静态成员AppController被标记为私有,这意味着它只能由Form1类看到(我假设它是它所在的类)

解决方案(如Alex D所示)可以是使成员内部而不是私有 。 这意味着可以通过同一个程序集中的任何类型查看该成员。 private仅对声明该成员的类型可见

如果你容易访问( 公开 ),你将得到如上所示的错误。 internal保持内部工作在您的程序集中,这意味着您不会遇到这些可访问性问题。