gpt4 book ai didi

c# - C# 中带参数的属性

转载 作者:太空宇宙 更新时间:2023-11-03 19:38:10 25 4
gpt4 key购买 nike

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;
}
}
}
}

然后让我们更改您的主类以使用地址:

public class Geek
{
public Address Address { get; } = new Address();
}

现在您可以像这样为 Address 属性使用索引器:

var hassn = new Geek();
hassn.Address[0] = "National Street";

关于c# - C# 中带参数的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58933112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com