查找类实例的属性的属性 [英] Finding the attributes on the properties of an instance of a class

查看:43
本文介绍了查找类实例的属性的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个类的实例,我想在运行时设置属性的属性.

Given an instance of a class I want to set properties on attributes at runtime.

所以我尝试了这个,但据我所知,它找到的是类上的属性而不是实例,所以我对属性所做的任何更改都不起作用.

So I tried this, but as far as I can tell this finds the attributes on the class not the instance, so any changes I make to the attribute properties have no effect.

var properties = myObject.GetType().GetProperties();

foreach (object prop in properties)
{
   var attribute =prop.GetCustomAttributes(typeof(MyAttribute), true)[0];
   //attribute.MyProp do some stuff
}

如果我尝试使用如下所示的类型描述符,则无法获取属性上的属性.

If I try using type descriptor like below, there is no way of getting to the attributes on the properties.

var myObject= (MyClass) object;
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(myObject);

//There is no props[0].GetCustomAttributes(

推荐答案

属性是应用于类型或类型成员的元数据,而不是实例.如果您将值应用于类的特定实例,是否应该考虑使用属性/字段?

Attributes are metadata you apply to a Type, or a Member of a Type, not an instance. If you are applying values to a specific instance of a class, shouldn't you consider using properties/fields?

这篇关于查找类实例的属性的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆