C#不能有两个同名的属性吗?

时间:2015-09-12 21:48:29

标签: c# vb.net

我将代码从VB.net转换为C#,但我遇到了一个小问题。在很多地方我们有私有数组,我们通过两个属性公开,一个获取并设置整个数组,另一个返回一个项目。这是原版中的一个例子......

Private pAmount as Double()
Friend Property Amount As Double()
    Get
        Return pAmount
    End Get
    Set(value As Double())
        pAmount = value
    End Set
End Property
Friend Property Amount(ByVal idx As Integer) As Double
    Get
        If idx < 0 OrElse idx >= pAmount.Length Then Return 0.0
        Return pAmount(idx)
    End Get
    Set(value As Double)
        If idx < 0 OrElse idx >= pAmount.Length Then Return
        pAmount(idx) = value
    End Set
End Property

我试过这个......

    private double[] pAmount;
internal double[] Amount {
    get { return pAmount; }
    set { pAmount = value; }
}
internal double Amount(int idx) {
    get {
        if (idx < 0 || idx >= pAmount.Length) return 0.0;
        return pAmount[idx];
    }
    set {
        if (idx < 0 || idx >= pAmount.Length) return 0.0;
        pAmount[idx] = value;
    }
}

但是这不起作用,它不允许第二个Amount。它们似乎应该是,因为输入和输出都是不同的。我在这里错过了其他一些让这个无效的东西吗?也许既然它是数组的访问者,我需要不同的语法?在代码中的其他地方,我收到关于&#34;方法组&#34;的消息,但我不确定我是否理解。

3 个答案:

答案 0 :(得分:3)

C#不能那样做。 VB.NET索引器属性更具表现力。

C#为您提供单个索引器名称。您可以应用一个属性来重命名所有索引器,但它们不能有不同的名称(我只是尝试过)。这真是一个神秘的东西。我从来没有见过它。我10年前才读过一次。

[System.Runtime.CompilerServices.IndexerName("TheItem")]
public int this [int index]   // Indexer declaration
{
}

这会重命名索引器......但这对你毫无帮助。

这不是一般应该完成的方式。使用这样的索引器是违反API准则的(我通常将其称为“滥用”)。

为什么您的数组属性名为Amount?它应该被称为Amount**s**,命名冲突就会消失。

您还可以使用方法移植此代码。它们可能会超载。

答案 1 :(得分:1)

根据C#5规范(第10.3节),这是不可能的:

  

•常量,字段,属性,事件或类型的名称必须不同   来自同一类中声明的所有其他成员的名称。

     

•   方法的名称必须与所有其他非方法的名称不同   在同一个班级宣布。另外,a的签名(§3.6)   方法必须与声明的所有其他方法的签名不同   在同一个类中,在同一个类中声明的两个方法可能不会   有不同的签名,只有ref和out。

答案 2 :(得分:-1)

您的第二个VB属性是&#39;参数化属性&#39;,而不是索引器。 C#不允许参数化属性,但您可以使用两种不同的方法轻松替换该属性:

private double[] pAmount;
internal double[] Amount
{
    get
    {
        return pAmount;
    }
    set
    {
        pAmount = value;
    }
}

internal double getAmount(int idx)
{
    if (idx < 0 || idx >= pAmount.Length)
    {
        return 0.0;
    }
    return pAmount[idx];
}
internal void setAmount(int idx, double value)
{
    if (idx < 0 || idx >= pAmount.Length)
    {
        return;
    }
    pAmount[idx] = value;
}