【问题标题】:Making a class with a private constructor in F#在 F# 中使用私有构造函数创建一个类
【发布时间】:2015-02-11 13:46:11
【问题描述】:

我想创建一个只有一个私有构造函数的类。现在我知道如何在 C# 中做到这一点,但我不知道如何在 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 static bool TryParse(string input, out ValidString validStr) {
            bool valid = input.Length <= 50 && input.All(Char.IsLetter);
            validStr = valid ? new ValidString(input) : null;

            return valid;
        }
    }

【问题讨论】:

    标签: class constructor f# private


    【解决方案1】:

    主构造函数的访问说明符跟在类型的名称和类型参数之后:

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

    【讨论】:

    • 正是我想要的!谢谢
    猜你喜欢
    • 2013-08-16
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2013-08-28
    • 2015-09-09
    • 1970-01-01
    • 2020-02-02
    • 2013-09-10
    相关资源
    最近更新 更多