我想在构建过程中验证类定义的条件,并在未验证的情况下显示构建错误。
在构建过程中,为每个由该属性定义的类创建属性实例。 我想检查一些东西,例如类没有超过 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; }
}
有可能吗?
如果不行,请问还有其他办法吗? (在构建过程中添加验证并在未验证的情况下显示错误)
最佳答案
这个解决方案可能有效
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ValidatePropertiesAttribute:ValidationAttribute
{
private Type TargetClass;
public ValidatePropertiesAttribute(Type targetClass)
{
TargetClass = targetClass;
if(Validate() == false)
{
throw new Exception("It's not valid!! add more properties to the type 'x'.");
}
}
public bool Validate()
{
//Use Target Class,
//if you need extract properties use TargetClass.GetProperties()...
//if you need create instance use Activator..
}
}
按如下方式使用该属性
[ValidateProperties(typeof(ExampleClass))]
public class ExampleClass
{
public string OnOneProperty { get; set; }
}
关于c# - 获取属性类中的类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26890385/