繁体   English   中英

可访问性不一致:参数类型的可访问性小于方法错误

[英]Inconsistent Accessibility: Parameter type is less accessible than method error

我收到此错误:

可访问性不一致:参数类型'Banjos4Hire.BanjoState'的访问权限比方法'Banjos4Hire.Banjo.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。
  • 一个整数不能接受带小数的数字。 这对您可能很好,但是请尝试使用名为decimal的数据类型。
  • 通常,人们不会在参数中添加单词“ in”。 这是样式选择,但是在专业领域,样式选择变得很重要。 我会选择单词,就像将它们分配给它们的字段一样: public Banjo(string description, int price, ...如果这样做,由于名称相同,您将需要更具体地指定类字段。您可以通过参考类实例使用关键字“这个”做到这一点。 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.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM