c# - 通过特定属性过滤类实例的属性并调用属性的方法

标签 c# reflection

我有一个包含一些属性的类。一些特定的属性用属性修饰。例如:

public class CoreAddress
{
    private ContactStringProperty _LastName;

    [ChangeRequestField]
    public ContactStringProperty LastName
    {
        //ContactStringProperty has a method SameValueAs(ContactStringProperty other)
        get { return this._LastName; }
    }
    .....
}

我想在我的类中有一个方法,它遍历该类的所有属性,过滤具有此自定义属性的属性并调用找到的属性的成员。这是我目前所拥有的:

foreach (var p in this.GetType().GetProperties())
        {
            //checking if it's a change request field
            if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0)
            {

                MethodInfo method = p.PropertyType.GetMethod("SameValueAs");
                //problem here        
                var res = method.Invoke(null, new object[] { other.LastName }); 

            }

        }

如果此方法是属性的实例方法,我必须提供一个目标(而不是代码中的 null)。如何在运行时获取此类实例的特定属性?

最佳答案

因为您已经有了 PropertyInfo,您可以调用 GetValue method .所以……

MethodInfo method = p.PropertyType.GetMethod("SameValueAs");
//problem solved
var propValue = p.GetValue(this);

var res = method.Invoke(propValue, new object[] { other.LastName });

关于c# - 通过特定属性过滤类实例的属性并调用属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12265147/

相关文章:

c# - "AsyncFuture<T>"还是什么? Future<T> 在后台线程中获得——它是一种模式吗?

c# - C++/命令行界面 : functions inherited from template class are not visible in C#

java - 将对象数组转换为自定义类型数组

java - 在java中使用反射调用Singleton类中的方法

Java 类作为变量

c# - 获取 ICollection<T> 实现类的类型参数

c# - WndProc 处理程序效率低下

c# - 如何更改数据网格特定行的颜色

c# - 统一2D。无法从其他类(class)访问我的音频。

java - 删除警告(类型安全 : Unchecked cast from capture#2-of ? 将模板扩展为 T)