假设我有以下课程:
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类实例化为非法 Gender MyGender = Gender.Male
从而制作
Gender Spaghetti = new Gender{Name = "Spaghetti", Abbreviation = 'S', Number = 123, ChildName = "Angel Hair" }
在编译时抛出错误?
答案 0 :(得分:8)
将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;
答案 1 :(得分:5)
给它一个私有构造函数:
public class Gender
{
// ...
private Gender() { }
}
通常,如果没有定义构造函数,则编译器会创建一个没有参数的“默认构造函数”。但如果你定义一个,那就没有默认值。如果那个是私人的,那个班级之外的任何东西都不能称之为。因此除了Gender
本身之外,没有任何东西可以构建Gender
的实例。
答案 2 :(得分:1)
使构造函数成为私有的。这就是它在SingleTon模式中的使用方式。