簡體   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