简体   繁体   English

查看是否将属性应用于类属性内字符串类型的属性

[英]See if attribute is being applied to a property that is of type String within the class attribute

say I have the attribute: 说我有属性:

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

then I can apply that attribute to a property as: 那么我可以将该属性应用于属性为:

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

Now how can I get information about the property Id from the attribute class. 现在如何从属性类获取有关属性ID的信息。 In other words I want to do something like: 换句话说,我想做类似的事情:

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; }
}

I actually need to know if the attribute is being applied to a property that is a string. 我实际上需要知道该属性是否被应用于字符串属性。

I know how to do that with reflection but I want to do that inside the attribute class. 我知道如何通过反射来做到这一点,但我想在属性类中做到这一点。 Is that possible. 那可能吗。 Hope I am explaining myself correctly 希望我能正确解释自己

You cannot do that without reflection because the code in the constructor will not be executed until you call GetCustomAttributes() , which is a part of reflection. 没有反射就无法做到这一点,因为在调用GetCustomAttributes()之前,构造函数中的代码将不会执行,这是反射的一部分。

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

Calling GetCustomAttributes on SampleClass causes an Author object to be constructed and initialized as above 在SampleClass上调用GetCustomAttributes会导致Author对象如上所述被构造和初始化

If you want your attribute class to contain the processing code, you could create a method receiving the property name. 如果希望属性类包含处理代码,则可以创建一个接收属性名称的方法。 The property name will be available at the time of calling GetCustomAttributes(). 该属性名称将在调用GetCustomAttributes()时可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM