基本上我可以说我有一个类A,它有一个B类的成员.是否有可能使用反射从B中的构造函数中获取创建B实例的A实例(如果有的话)?
class A
{
private B b = new B();
}
class B
{
public B()
{
// How could I get the instance of A (object), if any, that is creating me?
}
}
Run Code Online (Sandbox Code Playgroud)
伙计们,我的最终目标是创建一个通用的可绑定属性类,它能够找到其父级的PropertyChanged接口(如果已实现)以自动通知属性.假设我有一个名为MyBindableProp的类,它在实现INotifyPropertyChanged接口的类中使用.我想要的是通过将属性简单地声明为MyBindableProp {get; 组; }.如果我能找到托管对象,我知道如何做其余的事情.在构造函数中传递它是不在桌面上的.
你必须使用反射吗?你可以只通过实例A来B.
class A
{
private B b;
public A() {
b = new B(this);
}
}
class B
{
private readonly A a;
public B(A a) {
this.a = a;
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:我正在看你的评论,你说"我怎么能得到A(对象)的实例,如果有的话,那就是创造我?" 我猜测B并不总是从创建,A所以你可以暴露另一个B不带任何参数的构造函数:
class B
{
private readonly A _a;
public B() {}
public B(A a) {
_a = a;
}
}
Run Code Online (Sandbox Code Playgroud)
然后确保_a在使用之前已初始化:
if (_a != null)
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |