CollectionChanged获取持有集合的对象的实例



是否可以在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内引发该事件。

读一读德米特定律。

相关内容

  • 没有找到相关文章

最新更新