我希望在构建过程中对类定义进行条件验证,并在未通过验证时显示构建错误。
在构建过程中,为该属性定义的每个类创建一个实例。 例如,我想检查类是否没有超过4个属性(仅举例说明,这不是我的意图)。如何从每个类的属性构造函数中获取类型? (无需将其作为参数传递)。
例如:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidatePropertiesAttribute:ValidationAttribute
{
public ValidatePropertiesAttribute()
{
if(Validate()==false)
{
throw new Exception("It's not valid!! add more properties to the type 'x'.");
}
}
public bool Validate()
{
//check if there are at least 4 properties in class "X"
//Q: How can I get class "X"?
}
}
[ValidateProperties()]
public class ExampleClass
{
public string OnOneProperty { get; set; }
}
有可能吗?
如果不行,是否有其他方法可以实现呢? (在构建过程中添加验证,并在未通过验证时显示错误)