基本上问题在于标题:我如何检查一个类的属性有哪些属性?例如,这样的属性:
[SomeAttribute()]
public double Hours;
如何在调试期间看到Hours
具有属性SomeAttribute
?
答案 0 :(得分:1)
您可以使用一个简单的辅助扩展方法,该方法仅在debugging =>时执行。此方法将输出写入调试窗口
static class Extensions
{
[Conditional("DEBUG")]
public static void ShowAllProperties(this object obj)
{
var type = obj.GetType();
Debug.WriteLine(string.Format("Classname: {0}", type.Name));
var properties = type.GetProperties();
foreach (var property in properties)
{
//true will show inherited attributes as well
var attributes = property.GetCustomAttributes(true);
foreach (var attribute in attributes)
{
Debug.WriteLine(String.Format("'\t{0} - {1}", property, attribute));
}
}
}
}
然后可以在其构造函数中调用其他类。
class Book
{
[XmlElement("Author")]
public string Author { get; set; }
public Book()
{
this.ShowAllProperties();
}
}
这也适用于继承
class ComicBook
: Book
{
[XmlElement("ComicBookGenre")]
public string ComicbookGenre { get; set; }
public string ComicBookPublisher { get; set; }
}