C# 获取属性类中的类类型

C# 获取属性类中的类类型,c#,reflection,attributes,msbuild,C#,Reflection,Attributes,Msbuild,我想在构建过程中验证类定义的条件,并在未验证某些内容的情况下显示构建错误 在构建过程中,将为此属性定义的每个类创建属性实例。 我想检查一些东西,例如,类没有超过4个属性(例如,这不是我的意图)。如何从每个类的属性构造函数中获取类型? (不作为参数传递) 例如: [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class ValidatePropertiesAttribute:Valida

我想在构建过程中验证类定义的条件,并在未验证某些内容的情况下显示构建错误

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

有人知道什么是解决方案吗?那是不可能的。有一个强烈的暗示是,您没有充分考虑如何实现这一点。当您这样做时,您会发现将类型作为参数传递给Validate()方法是一个简单的解决方案。