在VB.Net中,属性可以像在函数中一样接收参数,方法是在属性定义的开头提到所有参数:
Private m_Address(2) As String
Property Address(ByVal index As Integer) As String
Get
If index >= 0 And index <= UBound(m_Address) Then
Return m_Address(index)
End If
End Get
Set(ByVal Value As String)
If index >= 0 And index <= UBound(m_Address( Then
m_Address(index) = Value
End If
End Set
End Property
如果要分配或读取属性值,请在括号中发送所需的参数:
Dim hassn As New PersonClass()
Dim counter As Integer
hassn.Address(0) = "National Street"
hassn.Address(1) = "Imbaba neighborhood"
hassn.Address(2) = "Giza"
For counter = 0 To 2
MsgBox(hassn.Address(counter))
Next
我尝试使用C#来做到这一点,但出现此错误:
public class Geek
{
private string[] m_address = new string[2];
public string[int x] address // error here
{
get
{
if (index >= 0 && index < index.length)
{
return m_address;
}
}
set {
if (index >= 0 && index < index.length)
{
m_address = value;
}
}
}
}
是的,在C#中,没有诸如Parameterized Properties这样的东西。您可以在C#中定义的唯一类型的参数化属性是索引器。
典型的C#属性只有一个默认参数value
。无论如何,属性是一组访问器,因此您可以定义这些方法而不是使用属性:
public class Geek
{
private string[] m_address = new string[2];
public void setAddress(int index)
{
if (index >= 0 && index < index.length)
{
m_address = value;
}
}
public void getAddress(int index)
{
if (index >= 0 && index < index.length)
{
return m_address;
}
}
}
另一个选择是创建一个Address
封装字段的类,并定义一个接受参数的自定义索引器。
好吧,让我们看看如何在这里使用索引器。首先让我们为地址创建一个类或结构:
public class Address
{
private string[] m_address = new string[2];
public string this[int index]
{
get => index >= 0 && index < m_address.Length ? m_address[index] : null;
set
{
if (index >= 0 && m_address.Length > index)
{
m_address[index] = value;
}
}
}
}
然后,让我们更改您的主类以使用Address:
public class Geek
{
public Address Address { get; } = new Address();
}
现在,您可以将Indexer用于Address属性,如下所示:
var hassn = new Geek();
hassn.Address[0] = "National Street";
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句