只读变量声明的顺序是否保证了值设置的顺序?
假设我有一些文件路径的只读变量,我是否能够保证根据声明的顺序分配值的顺序?
例如,
static readonly string basepath = @"my\base\directory\location";
static readonly string subpath1 = Path.Combine(basepath, @"abc\def");
static readonly string subpath2 = Path.Combine(basepath, @"ghi\klm";
这是一种安全的方法吗?或者,在 subpath1
和 subpath2
生成时,basepath
可能仍然是字符串的默认值吗?引用字符串?
我意识到我可以通过在构造函数中而不是在声明时分配值来保证顺序。但是,我相信如果我需要在静态类中声明变量(例如控制台应用程序的 Program.cs,它具有 static void Main() 过程而不是构造函数),则这种方法是不可能的。
更新:
我添加了 static 关键字(因为这就是我正在使用的关键字以及它编译的原因)以及建议的 Path.Combine 。
Say I were to have a few readonly variables for filepaths, would I be able to guarantee the order in which the values are assigned based on the order of declaration?
e.g.
static readonly string basepath = @"my\base\directory\location";
static readonly string subpath1 = Path.Combine(basepath, @"abc\def");
static readonly string subpath2 = Path.Combine(basepath, @"ghi\klm";
Is this a safe approach or is it possible that basepath
may still be the default value for a string at the time subpath1
and subpath2
make a reference to the string?
I realize I could probably guarantee the order by assigning the values in a constructor instead of at the time of declaration. However, I believe this approach wouldn't be possible if I needed to declare the variables inside of a static class (e.g. Program.cs for a console application, which has a static void Main() procedure instead of a constructor).
UPDATE:
I've added the static keyword (as that is what I am using and why it compiles) and also Path.Combine as suggested.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
顺序并不重要。运行时保证所有对象在使用时都被初始化。
您的具体案例实际上无法编译,因为无法保证这一点。
您对构造函数方法的看法是正确的。如果您需要静态变量,这也没有问题,因为您可以指定静态构造函数。
顺便说一句:连接目录的正确方法是使用 Path.Combine 而不是字符串连接。
The order is unimportant. The runtime guarantees that all objects are initialized when they are used.
Your concrete case is actually not compilable because this could not be guaranteed.
And you are right about the constructor approach. And if you need this for static variables it's no problem either because you can specify a static constructor.
And btw: The correct way of concatenating directories is to use Path.Combine and not string concatenation.
“这可能吗……”
不,编译器不会让您从 subpath1/2 声明访问基本路径。您可以使用常量而不是只读变量来完成此操作。
"is it possible.."
No, the compiler won't let you access basepath from the subpath1/2 declarations. You could do it with constants instead of read-only variables.
我怀疑您实际上想使用常量:
subpath1/2 肯定会填充基本路径前缀,无论代码中的声明顺序如何。
I suspect you actually want to use constants:
subpath1/2 will definitely have the filled in basepath prefix irrespective of declaration order in the code.