【发布时间】:2012-01-23 19:57:16
【问题描述】:
我有以下场景
组装A
public abstract class MyBaseEntity
{
//Uncompleted method
public void addChild<T>(T child)
{
try
{
Type tInfo = this.GetType();
PropertyInfo pInfo = tInfo.GetProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).Where(p => p.PropertyType == typeof(ISet<T>)).FirstOrDefault();
MethodInfo mInfo = tInfo.GetMethod("Add");
mInfo.Invoke(this, new object[] {child});
}
catch (Exception ex)
{
throw ex;
}
}
}
大会B
public class MyModel : MyBaseEntity
{
public virtual int p1 { get; set; }
public virtual int p2 { get; set; }
public virtual DateTime p3 { get; set; }
public virtual bool p4 { get; set; }
private readonly ISet<MyModelChild> _p5;
private readonly ISet<MyModelChild2> _p6;
public virtual string p7 { get; set; }
public MyModel()
{
this._p5 = new HashSet<MyModelChild>();
this._p6 = new HashSet<MyModelChild2>();
}
public virtual IEnumerable<MyModelChild> P5
{
get { return _p5; }
}
public virtual IEnumerable<MyModelChild2> P6
{
get { return _p6; }
}
}
在 MyBaseEntity 类中,我尝试获取私有 ISet 子级并调用方法“Add”。 我把“addChild”方法称为
myObject.addChild<MyModelChild>(child);
但GetProperties 方法不会提取私有属性。它可以提取所有公共属性,但不能提取私有属性。
谁能帮帮我?
谢谢!
【问题讨论】:
-
我认为您的程序集 A 代码中有错字(您没有对 pInfo 执行任何操作)。我还想知道,如果您要在其中进行反射而不是仅仅在继承类中覆盖它,那么将 AddChild 设为虚拟有什么意义。
-
@Malcom O'Hare 你是对的!我将该方法评论为“未完成”并删除了虚拟
标签: c# .net reflection properties