C# Reflection : Finding Attributes on a Member Field(C# 反射:在成员字段上查找属性)
问题描述
我可能问错了这个问题,但是您可以/如何在其自身中找到某个类的字段...例如...
I may be asking this incorrectly, but can/how can you find fields on a class within itself... for example...
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();
}
或者也许我只是做错了......我怎样才能调用一个方法,然后检查应用于自身的属性?
Or maybe I'm just doing this incorrectly... How can I call a method and then check for attributes applied to itself?
另外,为了这个问题 - 我只是好奇是否可以在不知道/访问父类的情况下找到属性信息!
Also, for the sake of the question - I'm just curious if it was possible to find attribute information without knowing/accessing the parent class!
推荐答案
如果我正确理解你的问题,我认为你试图做的事情是不可能的......
If I understand your question correctly, I think what you are trying to do is not possible...
在 Render
方法中,您希望获得应用于对象的可能属性.该属性属于 _SecondPart
字段,而该属性属于 HtmlForm
类.
In the Render
method, you want to get a possible attribute applied to the object. The attribute belongs to the field _SecondPart
witch belongs to the class HtmlForm
.
为此,您必须将调用对象传递给 Render
方法:
For that to work you would have to pass the calling object to the Render
method:
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# 反射:在成员字段上查找属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 反射:在成员字段上查找属性


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01