嵌套类混乱中的 c# 类访问
我创建了一个库类,其中...
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
”。如果有人可以帮助解释发生了什么事,我将不胜感激。
谢谢!
I have created a library class where...
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?
...
}
}
}
}
Here is the error I receive:
Cannot access a nonstatic member of outer type
"MyCircuitLibrary.CircuitLibrary.SerialCommands" via nested type
"MyCircuitLibrary.CircuitLibrary.SerialCommands.SensorSettingsCommands"
So it looks like it is searching for (and found?) Sensor
in SerialCommands
? But if I change it to CircuitLibrary.Sensor
it now knows it is in CircuitLibrary? When I right-click and "Go to definition" it finds it okay and doesn't say "Couldn't find Sensor
in SerialCommands
". If someone could help explain what is going on I would appreciate it.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的
SerialCommands
类具有非静态Sensor
属性。由于此属性比最外层的
Sensor
类更接近您的代码,因此编译器认为您正在使用该属性而不是类。由于没有
SerialCommands
实例就无法使用非静态属性,因此会出现错误。当您编写
CircuitLibrary.Sensor
时,它工作得很好,因为没有CircuitLibrary
属性来混淆编译器。Your
SerialCommands
class has a non-staticSensor
property.Since this property is closer to your code than the outer-most
Sensor
class, the compiler thinks you're using the property rather than the class.Since you can't a use the non-static property without a
SerialCommands
instance, you get an error.When you write
CircuitLibrary.Sensor
, it works fine, since there is noCircuitLibrary
property to confuse the compiler.