How to define a public static field to read?

In C #, you can define a readonly public static field as follows:

namespace MyNamespace
{
    public static class MyClass
    {
        public static readonly string MyValue = "Test";
    }
}

In F #, the code I can present that matches the best definition given above:

namespace MyNamespace

module MyClass =
    [<Literal>]
    let MyValue = "Test"

But this actually means the following C # snippet:

namespace MyNamespace
{
    public static class MyClass
    {
        public const string MyValue = "Test";
    }
}

How can I define a readinly public static field in F #? constnot an option for me, since I want to work with different assemblies .

+4
source share
2 answers

Just drop the attribute Literaland use the let-bound value:

module MyClass =
    let MyValue = "Test"

This will be compiled as the equivalent of a static property for getter only (generated by ILSpy C #):

public static string MyValue
{
    [DebuggerNonUserCode, CompilerGenerated]
    get
    {
        return "Test";
    }
}

( , ), readonly , ( getter). , ILSpy, .

, IL, - F #, ( , .. ). .

+4

,

public class Constants
{
    public const string CONSTANT_VALUE = "MY CONSTANT";
}

,

0

Source: https://habr.com/ru/post/1676200/


All Articles