自定义属性(例如 Displayname)未随 GetCustomAttribute 列出
我有一些代码来定义自定义属性,然后读取代码,但它无法工作。为了尝试解决该问题,我返回并尝试使用 DisplayName,但是,我仍然遇到相同的问题 GetCustomAttribute 或 GetCustomAttributes 无法列出它们。我在下面有一个例子。
例如,我在类中设置了 DisplayName 属性...
class TestClass
{
public TestClass() { }
[DisplayName("this is a test")]
public long testmethod{ get; set; }
}
然后我有一些代码来列出上面类中每个方法的 DisplayName 属性。
TestClass testClass = new TestClass();
Type type = testClass.GetType();
foreach (MethodInfo mInfo in type.GetMethods())
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(DisplayNameAttribute));
if (attr !=null)
{
MessageBox.Show(attr.DisplayName);
}
}
问题是没有列出 DisplayName 属性,上面的代码编译、运行并且不显示任何消息框。
我什至尝试使用 GetCustomAttributes 的 for every 循环,再次列出每个方法的所有属性,但 DisplayName 属性从未列出,但是,我确实获得了编译属性和其他此类系统属性。
有人知道我做错了什么吗?
更新-非常感谢 NerdFury 指出我使用的是方法而不是属性。一旦改变,一切就都有效了。
I have some code to define custom attributes and then to read in the code, it fails to work. To try and fix the problem I have gone back and tried to use DisplayName, however , I am still having the same issue GetCustomAttribute or GetCustomAttributes fails to list them. I have an example below.
I have a DisplayName Attribute set in a class, for example...
class TestClass
{
public TestClass() { }
[DisplayName("this is a test")]
public long testmethod{ get; set; }
}
I then have some code to list the DisplayName Attribute for each method in the class above.
TestClass testClass = new TestClass();
Type type = testClass.GetType();
foreach (MethodInfo mInfo in type.GetMethods())
{
DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(DisplayNameAttribute));
if (attr !=null)
{
MessageBox.Show(attr.DisplayName);
}
}
The problem is that there are no DisplayName Attributes listed, Above code compiles, runs and doesn't display any messageboxes.
I have even tried to use a for each loop with GetCustomAttributes, listing all the attributes for each method again the DisplayName Attribute is never listed, however, I do get the compilation attributes and other such system attributes.
Anyone have any idea what I am doing wrong?
UPDATE- Many thanks to NerdFury for pointing out that I was using Methods and not Properties. Once changed every thing worked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将属性放在属性上而不是方法上。尝试以下代码:
You are putting the attribute on a Property and not a Method. Try the following code: