相关疑难解决方法(0)

你怎么只找到同时拥有getter和setter的属性?

C#,.NET 3.5

我试图获得一个对象的所有属性,它们具有实例的getter和setter.我认为应该工作的代码是

PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
Run Code Online (Sandbox Code Playgroud)

但是,结果包括没有setter的属性.为了简单介绍一下可能影响它的继承结构(虽然我不知道如何):

public interface IModel
{
    string Name { get; }
}

public class BaseModel<TType> : IModel
{
    public virtual string Name { get { return "Foo"; } }

    public void ReflectionCopyTo(TType target)
    {
        PropertyInfo[] infos = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
        foreach (PropertyInfo info in infos)
            info.SetValue(target, info.GetValue(this, null), null);
    }
}

public class Child : BaseModel<Child>
{
    // I do nothing to …
Run Code Online (Sandbox Code Playgroud)

.net c# reflection

33
推荐指数
3
解决办法
1万
查看次数

标签 统计

.net ×1

c# ×1

reflection ×1