我可能问错了,但是你能/怎么能在类中找到字段......例如......
public class HtmlPart {
public void Render() {
//this.GetType().GetCustomAttributes(typeof(OptionalAttribute), false);
}
}
public class HtmlForm {
private HtmlPart _FirstPart = new HtmlPart();
[Optional] //<-- how do I find that?
private HtmlPart _SecondPart = new HtmlPart();
}
或者也许我只是做错了......我怎样才能调用一个方法然后检查应用到它自身的属性?
此外,为了这个问题 - 我只是好奇是否有可能在不知道/访问父类的情况下找到属性信息!
最佳答案
如果我正确理解你的问题,我认为你试图做的事情是不可能的......
在Render
方法中,您希望获得应用于对象的可能属性。该属性属于 _SecondPart
字段,属于 HtmlForm
类。
要使其工作,您必须将调用对象传递给 Render
方法:
public class HtmlPart {
public void Render(object obj) {
FieldInfo[] infos = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var fi in infos)
{
if (fi.GetValue(obj) == this && fi.IsDefined(typeof(OptionalAttribute), true))
Console.WriteLine("Optional is Defined");
}
}
}
关于C# 反射 : Finding Attributes on a Member Field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/803221/