奇妙的C#属性:属性 or 方法?

class TestClass
{
    //属性
    public int this[int a, int b]
    {
        get
        {
            return a + b;
        }
    }

    //方法
    public int Add(int a, int b)
    {
        return a + b;
    }
}

调用示例:

TestClass t = new TestClass();

Console.WriteLine(t[1, 2]);
Console.WriteLine(t.Add(1, 2));

测试说明

·只有this后边能跟中括号;
·this后边不能跟小括号,即不能写成方法;
·this[]只能为属性,不能为方法;

评论: 0 | 引用: 0 | 查看次数: 3472
发表评论
登录后再发表评论!