在F#中使用私有构造函数创建一个类

时间:2022-07-05 22:29:19

I want to make a class that has only one constructor which is private. Now I know how to do it in C# but I can't figure out how to do it in F#.

我想创建一个只有一个私有构造函数的类。现在我知道如何在C#中做到这一点,但我无法弄清楚如何在F#中做到这一点。

Basically this is what I want to do in F#:

基本上这就是我想在F#中做的事情:

    /// <summary>
    /// A valid string is a string of 50 characters or less that contains only letters of the latin alphabet. 
    /// </summary>
    public sealed class ValidString {
        private readonly string _value;

        private ValidString(string value) {
            _value = value;
        }

        public string Value { get { return _value; } }

        public bool TryParse(string input, out ValidString validStr) {
            bool valid = input.Length <= 50 && input.All(Char.IsLetter);
            validStr = valid ? new ValidString(input) : null;

            return valid;
        }
    }

1 个解决方案

#1


28  

The access specifier of the primary constructor follows the name and type parameters of the type:

主构造函数的访问说明符遵循类型的名称和类型参数:

type ValidString private (value: string) =
    ...

#1


28  

The access specifier of the primary constructor follows the name and type parameters of the type:

主构造函数的访问说明符遵循类型的名称和类型参数:

type ValidString private (value: string) =
    ...