如何定义公共静态只读字段? [英] How to define a public static readonly field?
问题描述
在C#中,可以这样定义一个公共的静态只读字段:
In C#, one can define a public static readonly field like this:
namespace MyNamespace
{
public static class MyClass
{
public static readonly string MyValue = "Test";
}
}
在F#中,我能想到的与上面定义最匹配的代码是:
In F#, the code I can think of which matches the definition above best is:
namespace MyNamespace
module MyClass =
[<Literal>]
let MyValue = "Test"
但这实际上转换为以下C#代码段:
But this actually translates to the following C# snippet:
namespace MyNamespace
{
public static class MyClass
{
public const string MyValue = "Test";
}
}
如何在F#中定义公共静态只读字段? const
不是我的选择,因为我想
How can I define a public static readonly field in F#? const
is not an option for me since I want to work with different assemblies.
推荐答案
只需删除 Literal
属性并使用一个让界值:
Just drop the Literal
attribute and use a let-bound value:
module MyClass =
let MyValue = "Test"
这将被编译为等效于仅静态获取方法的属性(ILSpy生成的C#):
This will compile as an equivalent of a static getter-only property (ILSpy-generated C#):
public static string MyValue
{
[DebuggerNonUserCode, CompilerGenerated]
get
{
return "Test";
}
}
如果该值涉及计算(而不是像您这样的文字),它将实际上绑定为模块(并在getter主体中引用)的内部类中的静态只读字段.您可以根据需要使用ILSpy验证自己.
If the value involves a computation (rather than being a literal as in your case), it will actually be bound as a static readonly field in the internal class underlying the module (and referred to in the getter body). You can verify that yourself with ILSpy if you like.
那是如果您对编译器生成的实际IL感兴趣的话-F#作为一种语言没有单独的只读字段概念(因为让绑定值,记录字段等是只读的)默认).它甚至没有保留关键字.
That's if you're interested in actual IL generated by the compiler - F# as a language doesn't have a separate notion of a read-only field (as let-bound values, record fields etc. are read-only by default). It doesn't even reserve the keyword.
这篇关于如何定义公共静态只读字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!