在属性类中获取类类型

3

我希望在构建过程中对类定义进行条件验证,并在未通过验证时显示构建错误。

在构建过程中,为该属性定义的每个类创建一个实例。 例如,我想检查类是否没有超过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; }
    }

有可能吗?

如果不行,是否有其他方法可以实现呢? (在构建过程中添加验证,并在未通过验证时显示错误)


有人知道这个问题的解决方案吗? - user436862
这是不可能的。强烈提示您还没有充分考虑如何实现它。当您这样做时,您会发现将类型作为参数传递给Validate()方法是微不足道的解决方案。 - Hans Passant
1个回答

3
这个解决方案可能有效。
[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; }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接