How to update a field of a class when a list of the class gets modified in C#?

本小妞迷上赌 提交于 2019-12-25 07:58:53

问题


I understand things in here are value types and not referenced so the field _num won't be modified when I just update the list. But my question is how to update the field _num when I modify the list that contains it gets modified?

class Foo
{
    public List<object> mylist;

    private int _num;

    public int num
    {
        get
        {
            return _num;
        }
        set
        {
            this._num = value;
            mylist[0] = value;
        }

    }

    public Foo()
    {
        mylist = new List<object>();
        mylist.Add(_num);
    }
}


class Program
{
    static void Main(string[] args)
    {
        Foo my = new Foo();
        my.num = 12;
        my.mylist[0] = 5;
        Console.WriteLine("" + my.mylist[0] + " " + my.num);    ==> output is "5 12"
        Console.ReadLine();
    }
}

What changes could be done so the list and the field is synced? Like my output should be "5 5" Thanks for the help!


回答1:


This may or may not be what you want... and I'm still not sure I see the need for modifying the fields by index, but if you really want to do that have you considered an indexer for your type? That is, the indexer would replace your list like so:

class Foo
{
    public int num;
    public string name;
    public bool isIt;

    public object this[int index]
    {
        get
        {
            switch(index)
            {
                case 0:
                    return num;
                case 1:
                    return name;
                case 2:
                    return isIt;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
        set
        {
            switch(index)
            {
                case 0:
                    num = (int) value;
                    break;
                case 1:
                    name = (string) value;
                    break;
                case 2:
                    isIt = (bool) value;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}

Then you can either say:

var foo = new Foo();
foo.num = 13;  // either works
foo[0] = 13;  // either works


来源:https://stackoverflow.com/questions/6777699/how-to-update-a-field-of-a-class-when-a-list-of-the-class-gets-modified-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!