规定类中需要属性 - 编译时

2 .net c# compiler-construction clr

有没有办法规定类的客户端应该为类中的一组属性指定值.例如(见下面的代码),我是否可以规定Employment类中的"EmploymentType"属性应该在编译时指定?我知道我可以使用参数化构造函数等.我特意在编译期间输出自定义警告或错误.那可能吗?

public class Employment
{
   public EmploymentType EmploymentType {get; set;}
}

public enum EmploymentType
{
    FullTime = 1,
    PartTime= 2
}

public class Client
{
    Employment e = new Employment();
// if i build the above code, i should get a error or warning saying you should specify value for EmploymentType
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*cah 5

正如cmsjr所说,你需要做的是:

public class Employment
{
    public Employment(EmploymentType employmentType)
    {
        this.EmploymentType = employmentType;
    }

    public EmploymentType EmploymentType { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

这会强制调用者在创建时传入值,如下所示:

Employment e = new Employment(EmploymentType.FullTime);
Run Code Online (Sandbox Code Playgroud)

在您需要具有默认构造函数(如序列化)但仍希望强制执行规则的情况下,您需要某种状态验证.例如,只要您尝试在Employment类上执行操作,就可以检查有效状态,如下所示:

public EmploymentType? EmploymentType { get; set; } // Nullable Type

public void PerformAction()
{
    if(this.Validate())
        // Perform action
}
protected bool Validate()
{
    if(!EmploymentType.HasValue)
        throw new InvalidOperationException("EmploymentType must be set.");
}
Run Code Online (Sandbox Code Playgroud)

如果你正在寻找抛出自定义编译器警告,这是不可能的.我在这里问了一个类似的问题自定义编译器警告