【发布时间】:2013-07-18 12:27:49
【问题描述】:
我正在 C# 中创建自定义属性。
所以我有这样的事情:
[AttributeUsage(AttributeTargets.Property)]
public class Something : Attribute
{
public Something
{
Assembly a = Assembly.GetCallingAssembly();
}
}
上面的代码会给我调用属性的程序集的程序集名称。
我想知道是否有一种方法可以获取添加属性的属性的名称和类型。例如,如果我有:
// This should return System.Int32 and MyString
[Something]
public int MyInt {get; set;}
// This should return me System.String, and MyString
[Something]
public string MyString {get; set;}
有什么方法可以在添加属性时获取这些值,还是我必须求助于循环遍历类型中的所有属性并查看哪些属性分配了属性?
提前致谢。
【问题讨论】:
-
您可以将类型添加到属性的构造函数中,然后通过调用 4.5 中的新泛型方法来检索它们
-
我希望它与 .Net 4.0 一起使用
-
@Garrry,你有快速样品吗?
-
是的,但是他在 4.0 中工作,而我的东西在 4.5 中,甚至无法在 4.0 中编译
-
一个 4.5 的答案可能对我这样的其他人有用;)事实上我不明白你在说哪个“4.5 中的新通用方法”
标签: c# .net reflection custom-attributes system.reflection