【问题标题】:How to overload default c# get set?如何重载默认的 c# 设置?
【发布时间】:2018-04-02 06:18:24
【问题描述】:

我想重载 c# 的默认 get set 方法。我无法通过不更改原始内容来编写get(int index)和set(int index,int value)我想重载c#的默认get set方法。我无法通过不更改原始内容来编写 get(int index) 和 set(int index, int value)。下面的代码无法编译。

    private int xx[2];

    public int Xx 
    {
        get (int index)
        {
            return xx[index == 1];
        }

        set (int index)
        {
            xx[index == 1] = value;
        }
    }

。下面的代码无法编译。

    private int xx[2];

    public int Xx 
    {
        get (int index)
        {
            return xx[index == 1];
        }

        set (int index)
        {
            xx[index == 1] = value;
        }
    }

【问题讨论】:

    标签: c# get set


    【解决方案1】:

    您所指的内容称为indexers。在 C# 中,要创建索引器,请使用关键字 this,后跟方括号,然后获取(和一个可选集):

    public int this[int index]
    {
        get { return arr[i]; }
        set { arr[i] = value; }
    }
    

    在您的情况下,您的代码应该做什么并不是很明显,但我认为您正在寻找这样的东西:

    private int xx[2];
    
    public int this[index] 
    {
        get { return xx[index]; }
        set { xx[index] = value; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-25
      • 1970-01-01
      • 1970-01-01
      • 2016-05-28
      • 2014-07-11
      • 2011-12-31
      • 1970-01-01
      相关资源
      最近更新 更多