c# - 获取属性类中的类类型

标签 c# reflection attributes msbuild

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

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

相关文章:

c# - 使用反射唯一标识方法或构造函数

javascript - 如何在没有类实例的情况下获取类的属性名称?

javascript - 如何向元素中的 id 添加附加属性?

javascript - 如何使用jquery获取大于给定值的元素的数据属性值?

python - lxml ElementMaker 属性格式化

c# - 如何在 Windows Phone 8 中设置背景图像?

c# - Unity C#中的更多脚本问题

Javascript 回溯

c# - WPF Datagrid 获取所有选中的行(不使用 WPF 绑定(bind))

c# - 让 .net DLL 作为 Windows 服务运行的简单方法