我如何重载[]操作在C# [英] How do I overload the [] operator in C#

查看:86
本文介绍了我如何重载[]操作在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想运营商加入到一个类。目前,我有,我想用[]操作符来替换的GetValue()方法。

  A级
{
    私人列表< INT>值=新的List< INT>();    公众诠释的GetValue(INT指数)
    {
        返回值[指数]
    }
}


解决方案

 公众诠释这个[INT键]
{
    得到
    {
        返回的GetValue(键);
    }
    组
    {
        的SetValue(键,值);
    }
}

I would like to add an operator to a class. I currently have a GetValue() method that I would like to replace with an [] operator.

class A
{
    private List<int> values = new List<int>();

    public int GetValue(int index)
    {
        return values[index];
    } 
}

解决方案

public int this[int key]
{
    get
    {
        return GetValue(key);
    }
    set
    {
        SetValue(key,value);
    }
}

这篇关于我如何重载[]操作在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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