如何在 C# 中声明常量 Guid?
是否可以在 C# 中声明常量 Guid?
我知道我可以声明一个static readonly Guid
,但是是否有一种语法允许我编写const Guid
?
Is it possible to declare a constant Guid in C#?
I understand that I can declare a static readonly Guid
, but is there a syntax that allows me to write const Guid
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不可以。 const 修饰符仅适用于“原始”类型(bool、int、float、double、long、decimal、short、byte)和字符串。基本上任何可以声明为文字的东西。
No. The
const
modifier only applies to "primitive" types (bool, int, float, double, long, decimal, short, byte) and strings. Basically anything you can declare as a literal.将其声明为
static readonly Guid
而不是const Guid
Declare it as
static readonly Guid
rather thanconst Guid
就是这样。
and that's that.
虽然您似乎无法做到这一点,但您可以在需要时进行解析:
While you can't seem to do that you can do that to be parsed whenever you need it:
我这样做是这样的:
I am doing it like this:
取决于你想要 const 的用途。
如果您希望拥有一个可以根据需要重用的已知 GUID,则上述将 GUID 存储为字符串并根据需要解析为 GUID 的解决方案是有效的。
如果您需要默认参数值,那将不起作用。另一种方法是使用可为 null 的 Guid 并使用 null 作为常量值。
Depends on what you want a const for.
If you want to have a known GUID that you can reuse as needed, the above solution of storing the GUID as a string and parsing to GUID as needed works.
If you need a default parameter value, that won't work. The alternative is to use a nullable Guid and use null as your constant value.
Guid.Parse("5C60F693-BEF5-E011-A485-80EE7300C695")
Guid.Parse("5C60F693-BEF5-E011-A485-80EE7300C695")