可访问性不一致:参数类型的可访问性低于方法错误
本文关键字:访问 错误 于方法 方法 不一致 参数 类型 | 更新日期: 2023-09-27 17:59:09
我收到这个错误:
可访问性不一致:参数类型"Banjos4Hire.BanjoState"的可访问性低于方法"Banjos4Hire.Banjo(string,int,int,Banjos4Hire.BanjoState)"
使用此代码:
public Banjo(string inDescription, int inPrice, int inBanjoID, BanjoState inState)
{
description = inDescription;
price = inPrice;
banjoID = inBanjoID;
BanjoState state = inState;
}
有人知道我该怎么解决吗?
感谢
如果BanjoState是一个枚举,我对您的代码的其余部分进行了一些假设,并添加了注释来显示错误:
namespace BanjoStore
{
class Program
{
static void Main(string[] args)
{
//Create a Banjo!
var myFirstBanjo = new Banjo("it's my first!", 4, 67, Banjo.BanjoState.Used);
//Oh no! The above line didn't work because I can't access BanjoState!
//I can't used the enum to pass in the value because it's private to the
//Banjo class. THAT is why the error was visible in the constructor.
//Visual Studio knew this would happen!
}
}
class Banjo
{
//These are private by default since there isn't a keyword specified
//and they're inside a class:
string description;
int price;
//This is also private, with the access typed in front so I don't forget:
private int banjoID;
//This enum is private, but it SHOULD be:
//public enum BanjoState
//Even better, it can be internal if only used in this assembly
enum BanjoState
{
Used,
New
}
public Banjo(string inDescription, int inPrice, int inBanjoID,
BanjoState inState)
{
description = inDescription;
price = inPrice;
banjoID = inBanjoID;
BanjoState state = inState;
}
}
}
提示
- 正如我提到的,您需要访问BanjoState枚举。完成工作所需的最少访问权限是最好的。在这种情况下,这可能意味着内部。如果你只熟悉公共和私人,那就公开吧。您需要这种访问权限,以便在创建Banjo类的实例时,实际上可以为最后一个参数指定BanjoState
- int不能接受带小数的数字。这对您来说可能很好,但请尝试名为decimal的数据类型
- 通常人们不会在参数中添加"in"一词。这是一种风格选择,但在职业界,风格选择变得很重要。我会选择与你分配给它们的字段类似的单词:
public Banjo(string description, int price, ...
如果你这样做,你需要更具体地指定你的类字段,因为名称是相同的。您可以通过使用关键字"this"引用类实例来实现这一点。this.description = description;
- 您可能不希望描述、价格等字段是私有的。如果你这样做了,人们通常会在前面加下划线:
string _description
如果BanjoState是您正在引用的另一个项目中的一个类,则它位于与BanjoS不同的程序集中,并且您不能用您范围之外的东西创建构造函数。
在这种情况下,您需要将"BanjoState"类声明为公共类。看看声明,我想你不会发现这个类没有public关键字。不能让参数(BanjoState类型的对象)的可访问性低于使用它进行构造的类,因为这样就无法创建公共类的实例。
从MSDN关于类的页面:
直接在命名空间中声明的类,而不是嵌套的类在其他类中,可以是公共的,也可以是内部的。课程为默认情况下为内部。
代码来自上面页面上的示例(但为您个性化):
class BanjoState //This class is internal, not public!
{
// Methods, properties, fields, events, delegates
// and nested classes go here.
}