这段代码是否会创建一个getter?我想把它翻译成C#

时间:2016-07-19 11:53:56

标签: c# vb6 vb6-migration

Private Samples As Collection
Public Function Count() As Integer

    Count = Samples.Count

End Function

我正在尝试将此代码转换为C#。我也试图理解这段代码的逻辑。我目前有这段代码,

Public int Count {get; set;}

这是用c#编写的。

3 个答案:

答案 0 :(得分:4)

不,如果它说Function,则表示功能。相反,如果它说Property它是一个属性而可以那么(可选)只包含一个getter。

精确的等价物是:

public int Count() {
  return Samples.Count;
}

你可能被绊倒的地方是查看调用代码 - 在VB中,括号在调用无参数函数时是可选的,所以你可能会看到调用上述函数的代码只是说Count而不是{ {1}}。

答案 1 :(得分:2)

private Collection<object> Samples { get; set; }
public int Count() {
  return  Samples.Count;
}

答案 2 :(得分:1)

这是作为属性实现的等价物(就像你试图做的那样):

public int Count
{
    get
    {
        return Samples.Count;
    }
}

确切的等价物:作为一种常规方法,你可以这样做:

public int Count()
{
    return Samples.Count;
}

但是,下面的代码会创建一个默认的setter和getter。在你的情况下,你不需要一个setter,并且getter不会返回_count hidden字段的值。但它返回列表的计数。

Public int Count {get; set;}

这些是自动实现的属性,相当于:

private int _count;
public int get_Count()
{
   return _count();
}

public void set_Count(int value)
{
   _count = value;
}