此代码是否创建 getter?我正在尝试将其翻译成 C#
Is this code creating a getter? I am trying to translate this to C#
Private Samples As Collection
Public Function Count() As Integer
Count = Samples.Count
End Function
我正在尝试将这段代码翻译成 C#。我也试图理解这段代码的逻辑。我目前有这段代码,
Public int Count {get; set;}
这是用c#写的。
这是作为 属性 实现的等效项(就像您尝试做的那样):
public int Count
{
get
{
return Samples.Count;
}
}
完全等效:作为常规方法,您可以这样做:
public int Count()
{
return Samples.Count;
}
但是,下面的代码创建了默认的 setter 和 getter。在您的情况下,您不需要 setter,并且 getter 不需要 return _count 隐藏字段的值。但它 return 是列表的计数。
Public int Count {get; set;}
这些是自动实现的属性,相当于:
private int _count;
public int get_Count()
{
return _count();
}
public void set_Count(int value)
{
_count = value;
}
private Collection<object> Samples { get; set; }
public int Count() {
return Samples.Count;
}
不是,如果说Function
,就是函数的意思。相反,如果它说 Property
它将是 属性 并且 可以 然后(可选)仅包含 getter.
精确的等价物是:
public int Count() {
return Samples.Count;
}
您可能被绊倒的地方是查看调用代码 - 在 VB 中,调用无参数函数时括号是可选的,因此您可能会看到调用上述函数的代码只是说 Count
而不是 Count()
.
Private Samples As Collection
Public Function Count() As Integer
Count = Samples.Count
End Function
我正在尝试将这段代码翻译成 C#。我也试图理解这段代码的逻辑。我目前有这段代码,
Public int Count {get; set;}
这是用c#写的。
这是作为 属性 实现的等效项(就像您尝试做的那样):
public int Count
{
get
{
return Samples.Count;
}
}
完全等效:作为常规方法,您可以这样做:
public int Count()
{
return Samples.Count;
}
但是,下面的代码创建了默认的 setter 和 getter。在您的情况下,您不需要 setter,并且 getter 不需要 return _count 隐藏字段的值。但它 return 是列表的计数。
Public int Count {get; set;}
这些是自动实现的属性,相当于:
private int _count;
public int get_Count()
{
return _count();
}
public void set_Count(int value)
{
_count = value;
}
private Collection<object> Samples { get; set; }
public int Count() {
return Samples.Count;
}
不是,如果说Function
,就是函数的意思。相反,如果它说 Property
它将是 属性 并且 可以 然后(可选)仅包含 getter.
精确的等价物是:
public int Count() {
return Samples.Count;
}
您可能被绊倒的地方是查看调用代码 - 在 VB 中,调用无参数函数时括号是可选的,因此您可能会看到调用上述函数的代码只是说 Count
而不是 Count()
.