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)