在对象的属性更改时执行函数

时间:2012-10-19 02:52:37

标签: c# .net

我有一个如下所示的对象模型:

public class MyModel
{
    public List<MyOtherObject> TheListOfOtherObjects { get; set; }

    public List<int> MyOtherObjectIDs { get; set; }

    public void GetListOfMyOtherObjectIDs() 
    {
       // function that extracts the IDs of objects in
       // the list and assigns it to MyOtherObjectIDs
    }
}

目前,当查询填充GetListOfMyOtherObjectIDs时,我有一些执行TheListOfOtherObjects的代码。现在我在代码中还有另一个位置来填充此列表,当它执行时,它还需要执行GetListOfMyOtherObjectIDs函数。

有没有办法让这个过程自动生成,以便在TheListOfOtherObjects被弹出时,无论哪个代码触发它,对象模型都会自动执行GetListOfMyOtherObjectIDs

1 个答案:

答案 0 :(得分:3)

使用您自己的set访问者:

public class MyModel
{
    private List<MyOtherObject> _TheListOfOtherObjects;
    public List<MyOtherObject> TheListOfOtherObjects {
        get { return _TheListOfOtherObjects; }
        set { _TheListOfOtherObjects = value; GetListOfMyOtherObjectIDs(); }
    }

    public List<int> MyOtherObjectIDs { get; set; }

    public void GetListOfMyOtherObjectIDs() 
    {
       // function that extracts the IDs of objects in
       // the list and assigns it to MyOtherObjectIDs
    }
}
相关问题