查看属性是否应用于class属性中String类型的属性

时间:2012-02-09 05:45:56

标签: c# reflection attributes

说我有属性:

public class Column_Attribute : Attribute
{
    public string DbType { get; set; }
    public bool IsPrimaryKey { get; set; }
}

然后我可以将该属性应用于属性:

 [Column_Attribute(DbType = "Integer", IsPrimaryKey = true)]
 public int Id { get; set; }   

现在我如何从属性类中获取有关属性Id的信息。换句话说,我想做类似的事情:

public class Column_Attribute : Attribute
{
    // constructor
    public Column_Attribute(){
      // if the property has the name Id do something...
      // OR
      // if this is an attribute of a property do something
      // if this is an attribute of a field do something else

      // If this attribute is targeting a property that is a string do something
    }

    public string DbType { get; set; }
    public bool IsPrimaryKey { get; set; }
}

我实际上需要知道属性是否应用于字符串属性。

我知道如何用反射做到这一点,但我想在属性类中做到这一点。那可能吗。希望我能正确解释自己

1 个答案:

答案 0 :(得分:1)

如果没有反射,你就不能这样做,因为在你调用GetCustomAttributes()之前,构造函数中的代码不会被执行,这是反射的一部分。

请参阅http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx

  

在SampleClass上调用GetCustomAttributes会导致Author对象   按上述方式构建和初始化

如果希望属性类包含处理代码,则可以创建接收属性名称的方法。在调用GetCustomAttributes()时,属性名称将可用。