簡體   English   中英

嵌套類混淆導致的c#類訪問

[英]c# Class Access from Nested Class Confusion

我創建了一個圖書館課程,其中...

public class CircuitLibrary
{
   // Fields, properties, methods, etc.
   ...

   // Nested classes.
   public class Sensor
   {
      // Enums.
      public enum Sensors { Sensor1, Sensor2, Sensor3, ... };

      ...
   }

   public class SerialCommands
   {
      // Fields, properties, etc.
      ...

      // Nested classes.
      public class SensorSettingsCommands
      {
         // Fields, properties, etc.
         ...

         public void SomeMethod()
         {
            ...
            if( Sensor.Sensors.IsOn ) // Doesn't like this. OK if I change to CircuitLibrary.Sensor.Sensors.IsOn. Why?
               ...
          }
      }
   }
}

這是我收到的錯誤:

Cannot access a nonstatic member of outer type
"MyCircuitLibrary.CircuitLibrary.SerialCommands" via nested type
"MyCircuitLibrary.CircuitLibrary.SerialCommands.SensorSettingsCommands" 

如此看來,它正在SerialCommands搜索(並找到?) Sensor 但是,如果我將其更改為CircuitLibrary.Sensor它現在知道它在CircuitLibrary中? 當我單擊鼠標右鍵並單擊“轉到定義”時,它沒有問題,沒有說“在SerialCommands找不到Sensor ”。 如果有人可以幫助解釋發生了什么,我將不勝感激。

謝謝!

您的SerialCommands類具有非靜態Sensor屬性。

由於此屬性比最外層的Sensor類更接近您的代碼,因此編譯器認為您使用的是屬性而不是類。
由於在沒有SerialCommands實例的情況下無法使用非靜態屬性,因此會出現錯誤。

當你編寫CircuitLibrary.Sensor ,它工作正常,因為沒有CircuitLibrary屬性來混淆編譯器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM