[英]C# class attributes, get them by index
是否可以通过索引访问属性?
以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
但是, 这是一件可怕的事情,您甚至不应该考虑以这种方式使用它!*
您可以在Person类中仅包含一个字符串Dictionary,并在更改属性时将字符串值写入其中。 像这样:
class Person
{
Person()
{
properties.Add(0, "defaultBirthNo");
}
Dictionary<int, string> properties = new Dictionary<int,string>();
private int birthNo;
public int BirthNo
{
get { return birthNo;}
set {
birthNo = value;
properties[0] = birthNo.ToString();
}
}
}
设置属性时
person.BirthNo = 1;
例如,您可以使用以下方法检索它:
string retreivedBrithNo = person.properties[0];
这是令人难以置信的混乱,我不知道为什么您要这样做,但是无论如何这都是答案! :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.