C# 如何使用distinct set和get重载[]运算符?

C# 如何使用distinct set和get重载[]运算符?,c#,.net,operator-overloading,C#,.net,Operator Overloading,我想使用不同的方法来实现各自的get和set用例,如下所示: public int this[int i] { get { return i + 1; } } public string this[int i] { set { } } class It { string SomeProperty; } class Bar { Action this[string key] { set { // ...

我想使用不同的方法来实现各自的get和set用例,如下所示:

public int this[int i]
{
    get { return i + 1; }
}

public string this[int i]
{
    set { }
}
class It {
    string SomeProperty;
}

class Bar {
    Action this[string key] {
        set {
            // ...
        }
    }
    string this[string key] {
        get {
            return new It ();
        }
    }
}

Bar ["key"] = () => {};
Bar ["key"].SomeProperty = 5;
这导致
错误CS0111:类型“Foo”已使用相同的参数类型定义了名为“This”的成员

这一功能似乎无法以天真的方式实现。有解决办法吗

我想这样使用它:

public int this[int i]
{
    get { return i + 1; }
}

public string this[int i]
{
    set { }
}
class It {
    string SomeProperty;
}

class Bar {
    Action this[string key] {
        set {
            // ...
        }
    }
    string this[string key] {
        get {
            return new It ();
        }
    }
}

Bar ["key"] = () => {};
Bar ["key"].SomeProperty = 5;

索引器重载是一个接受参数的特殊属性。在VB.NET中,由于VB处理集合的方式,该属性被命名为
项(…)
。如果您查看
IList
的界面,您会注意到它在那里也被称为
Item

因此,它必须遵循与属性和方法重载相同的规则。方法的返回类型不被视为其调用签名的一部分,因此重载解析(编译器如何决定调用哪个版本的方法)无法区分索引器实现之间的差异

索引器的目的是提供对类集合对象中存储的值的访问。如果您可以获取并设置与给定键或索引相关联的值,则期望您应该返回与设置的值相同的值

您的示例试图实现一种类型二元性,这不是索引器的意图,在.NET类型系统中也无法实现。类型不能同时是
操作
字符串
。它与基本的面向对象原则背道而驰,试图将某件事变成两件事

如果要将操作与字符串关联,则应创建一个类型,该类型仅执行以下操作:

public class NamedAction
{
    private readonly Action _action;
    public string Name { get; }

    public NamedAction(Action action, string name)
    {
        _action = action;
        Name = name;
    }

    public void Invoke()
    {
        _action.Invoke();
    }
}

现在,您可以使用一个索引器来获取和设置
NamedAction
实例,一切都变得更有意义。

不,您不能这样做。您不能有多个仅因返回类型而异的索引器。您不能这样做。请如果你想要一个属性得到一个int,但是设置了一个字符串,那你就太倒霉了。把它们包装在子类型中,这样可以有效地给它们命名。为什么不改为使用方法?@kevintjuh93您可以有多个
this[…]
,但它们需要根据参数类型/计数而变化。新示例中的getter返回一个字符串。另外,您能解释一下将值设置为动作,但得到完全不同的对象的用例吗?你能举一个具体的例子说明你打算用它做什么吗?