gpt4 book ai didi

C#类属性,通过索引获取

转载 作者:行者123 更新时间:2023-12-02 05:08:23 24 4
gpt4 key购买 nike

是否可以通过索引访问属性?

以Person类为例,它可以有属性“BirthNo”和“Gender”。如果我想访问 BirthNo 的值,是否可以以任何方式编写 p.[0].Value 还是我必须编写 person.BirthNo.Value?

Person p = new Person
//I have this:
string birthNo = p.BirthNo.Value;
//I want this:
string birthNo = p.[0].Value;

最佳答案

p.[0].Value 不是正确的 c# 代码,因此您绝对不能这样写。

您可以尝试使用 indexers , 但是你必须自己写很多逻辑,比如:

public T this[int i]
{
get
{
switch(i)
{
case 0: return BirthNo;
default: throw new ArgumentException("i");
}
}
}

调用代码看起来是这样的:

p[0].Value

但是,这是可怕的事情,你甚至不应该考虑那样使用它!*

关于C#类属性,通过索引获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15909295/

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