Mark parameters as NOT nullable in C#/.NET?

后端 未结 6 2019
粉色の甜心
粉色の甜心 2020-12-02 21:53

Is there a simple attribute or data contract that I can assign to a function parameter that prevents null from being passed in C#/.NET? Ideally this would also

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-02 22:11

    Check out the validators in the enterprise library. You can do something like :

    private MyType _someVariable = TenantType.None;
    [NotNullValidator(MessageTemplate = "Some Variable can not be empty")]
    public MyType SomeVariable {
        get {
            return _someVariable;
        }
        set {
            _someVariable = value;
        }
    }
    

    Then in your code when you want to validate it:

    Microsoft.Practices.EnterpriseLibrary.Validation.Validator myValidator = ValidationFactory.CreateValidator();
    
    ValidationResults vrInfo = InternalValidator.Validate(myObject);
    

提交回复
热议问题