gpt4 book ai didi

C# 如何访问公共(public)结构的静态字段

转载 作者:太空狗 更新时间:2023-10-29 22:08:25 27 4
gpt4 key购买 nike

我正在尝试访问已定义为公共(public)的 structstatic 字段。但是,我仍然“由于其保护级别而无法访问”有人可以帮助我吗?

public class Program
{
public struct AT_CMD
{
static int x = 7;
static byte[] cmd_mode = new byte[3] { 0x2B, 0x2B, 0x2B };
static byte[] end_device_assoc = new byte[4] { 0x41, 0x54, 0x41, 0x31 };
//should be 0 for end device, default is 0
static byte[] data_rate = new byte[4] { 0x41, 0x54, 0x42, 0x44 }; //3 for 9600, 5 for 38400
static byte[] channel = new byte[4] { 0x41, 0x54, 0x43, 0x48 }; //0x0B-0x1A
static byte[] Dest_addr_high = new byte[4] { 0x41, 0x54, 0x44, 0x48 }; //0 FOR 16bit
static byte[] Dest_addr_low = new byte[4] { 0x41, 0x54, 0x44, 0x4C };
static byte[] my_addr = new byte[4] { 0x41, 0x54, 0x4D, 0x59 }; // 0-0xFFFF
static byte[] carriage_return = new byte[1] { 0x0D };
}

static void Main()
{
int y = AT_CMD.x;
}
}

最佳答案

将其更改为:

  public struct AT_CMD
{
public static int x = 7;

// ...
}

只是制作一个struct public 不会影响它的成员,struct 的成员将是private 默认情况下,除非您另有说明。

更新:解决默认访问的混淆问题,internalstructclass 的默认访问如果在命名空间级别声明(不嵌套在另一个类/结构中)本身:

Classes and structs that are declared directly within a namespace (in other words, that are not nested within other classes or structs) can be either public or internal. Internal is the default if no access modifier is specified.

然而,classstruct 中的字段始终默认为 private:

The access level for class members and struct members, including nested classes and structs, is private by default.

来自MSDN .

关于C# 如何访问公共(public)结构的静态字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993442/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com