简体   繁体   English

如何重载默认C#获取设置?

[英]How to overload default c# get set?

I want to overload default get set methods of c#. 我想重载C#的默认get设置方法。 I could not achieve to write get(int index), and set(int index, int value) by not changing the original contenI want to overload default get set methods of c#. 我无法通过不更改原始内容来实现写入get(int index)和set(int index,int value),而我想重载c#的默认get set方法。 I could not achieve to write get(int index), and set(int index, int value) by not changing the original content. 通过不更改原始内容,我无法实现写get(int index)和set(int index,int value)。 Below code just does not compile. 下面的代码只是无法编译。

    private int xx[2];

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

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

. Below code just does not compile. 下面的代码只是无法编译。

    private int xx[2];

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

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

What you refer to is called indexers . 您指的是索引器 In c#, to create indexers, you use the keyword this , followed by square brackets and then get (and an optional set): 在c#中,要创建索引器,请使用关键字this ,后跟方括号,然后获取(和一个可选集):

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

In your case it's not really obvious what your code should go, but I think you are looking for something like this: 在您的情况下,您应该去执行的代码不是很明显,但是我认为您正在寻找这样的东西:

private int xx[2];

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM