gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:58:52 25 4
gpt4 key购买 nike

假设我有以下类(class):

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;

关于c# - 可以使子类仅通过静态属性实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18856185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com