在C#中修改类列表时,如何更新类的字段? [英] How to update a field of a class when a list of the class gets modified in C#?

查看:273
本文介绍了在C#中修改类列表时,如何更新类的字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解这里的内容是值类型,没有被引用,因此当我更新列表时,不会修改字段_num.但是我的问题是,当我修改包含_num的列表时,该如何更新该字段?

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();
    }
}

可以进行哪些更改,以使列表和字段同步?就像我的输出应该是"5 5" 感谢您的帮助!

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

推荐答案

这可能是您想要的,也可能不是...我仍然不确定是否需要按索引修改字段,但是如果您真的想这样做,您是否考虑过为您的类型创建索引器?也就是说,索引器将替换您的列表,如下所示:

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();
            }
        }
    }
}

然后您可以说:

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

这篇关于在C#中修改类列表时,如何更新类的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆