可以使子类仅通过静态属性实例化

本文关键字:静态 属性 实例化 子类 可以使 | 更新日期: 2023-09-27 18:31:44

假设我有以下类:

public class Gender
{
    public readonly string Name { get; set;}
    public readonly char Abbreviation { get; set;} 
    public readonly string ChildName { get; set;}
    public readonly int Number { get; set;}
    public static Gender Male = new Gender { Name = "Male", Abbreviation = 'M', Number = 1, ChildName = "Boy" };
    public static Gender Female = new Gender { Name = "Female", Abbreviation = 'F', Number = 2, ChildName = "Girl" };
    public static Gender Unknown = new Gender { Name = "Unknown", Abbreviation = 'U', Number = 0, ChildName = "Unknown" };
}

除了

Gender MyGender = Gender.Male

从而使

Gender Spaghetti = new Gender{Name = "Spaghetti", Abbreviation = 'S', Number = 123, ChildName = "Angel Hair" }

在编译时抛出错误?

可以使子类仅通过静态属性实例化

private构造函数添加到类Gender

public class Gender
{
    public readonly string Name { get; set;}
    public readonly char Abbreviation { get; set;} 
    public readonly string ChildName { get; set;}
    public readonly int Number { get; set;}
    private Gender()
    {
    }
    public static Gender Male = new Gender { Name = "Male", Abbreviation = 'M', Number = 1, ChildName = "Boy" };
    public static Gender Female = new Gender { Name = "Female", Abbreviation = 'F', Number = 2, ChildName = "Girl" };
    public static Gender Unknown = new Gender { Name = "Unknown", Abbreviation = 'U', Number = 0, ChildName = "Unknown" };
}

您也可以将readonly添加到Male/Female/Unknown声明中,以使以下代码无法进行:

Gender.Male = Gender.Female;

给它一个私有构造函数:

public class Gender
{
    // ...
    private Gender() {  }
}

通常,如果没有定义构造函数,则编译器会创建一个没有参数的"默认构造函数"。 但是,如果您定义一个,则没有默认值。 如果那个是私有的,那么该类之外的任何东西都不能调用它。 因此,除了Gender本身之外,没有什么可以构建Gender实例。

将构造函数设为私有。这就是它在单吨模式中的使用方式。