是否可以在CollectionChanged事件中获取项的Instance
?
例如:
public class Foo
{
public string Name { get; set; }
public ObservableCollection<Bar> Bars { get; set; }
public Foo()
{
Bars += HelperFoo.Bars_CollectionChanged;
}
}
public class Bar
{
public string Name { get; set; }
}
public static class HelperFoo
{
public static voic Bars_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
//sender is the collection Foo.Bars
//can I get the Instance of Foo?
}
}
(我不介意使用反射(
如果这不可能,是否有方法获取初始化其他对象的对象的实例?
例如:
public class Foo
{
public string Name { get; set; }
public Foo()
{
var bar = new Bar(); //yes I know, I could write new Bar(this) and provide an overload for this
}
}
public class Bar
{
public string Name { get; set; }
public Bar()
{
//Get the Foo, since the constructor is called within Foo, is this possible?
//without providing an overload that takes an object, and just change it to `(new Bar(this))`
}
}
我同意@Gaz的观点,但如果你真的想做你描述的事情,那么就在HelperFoo类中添加一个Dictionary。然后在Foo类中添加this作为创建者,如下所示。
public static class HelperFoo
{
private static Dictionary<ObservableCollection<Bar>, object> lookupCreators = new Dictionary<ObservableCollection<Bar>, object>();
public static void AddBarsCreator(ObservableCollection<Bar> bars, object creator)
{
lookupCreators.Add(bars, creator);
}
public static void Bars_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
ObservableCollection<Bar> bars = (ObservableCollection<Bar>)sender;
if (lookupCreators.ContainsKey(bars))
{
}
}
}
public class Foo
{
public ObservableCollection<Bar> Bars { get; set; }
public Foo()
{
Bars = new ObservableCollection<Bar>();
HelperFoo.AddBarsCreator(Bars, this);
Bars.CollectionChanged += HelperFoo.Bars_CollectionChanged;
}
}
您的代码结构似乎很奇怪。
如果HelperFoo
类需要对Foo
执行某些操作,则将其传递给Foo
,并让它自己订阅Bar
事件。
如果HelperFoo
不应该知道Bars
的任何信息,那么在Foo
上公开一个事件并订阅它。当Bars
发生更改时,您可以在Foo
内引发该事件。
读一读德米特定律。