查看属性是否应用于类属性中 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; }
}
我实际上需要知道该属性是否应用于字符串属性。
我知道如何通过反射来做到这一点,但我想这样做属性类内部。这可能吗。希望我能正确解释自己
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. 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果没有反射,则无法执行此操作,因为构造函数中的代码只有调用
GetCustomAttributes()
才会执行,这是反射的一部分。请参阅 http://msdn.microsoft.com/ en-us/library/z919e8tw(v=vs.80).aspx
如果您希望属性类包含处理代码,您可以创建一个接收属性名称的方法。属性名称将在调用 GetCustomAttributes() 时可用。
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.see http://msdn.microsoft.com/en-us/library/z919e8tw(v=vs.80).aspx
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().