2012-02-09 47 views
0

说中String类型的属性属性我有属性:看看是否被应用到是类属性

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

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

看到http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx

调用GetCustomAttributes上SampleClass导致作者对象 构造和初始化上述

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