在客户类的属性上使用索引器

时间:2014-06-19 08:16:45

标签: c# properties indexer

google.ing已经有一段时间了,似乎没有什么能与我的具体问题相符。

我创建了自己的类,其中包含一些属性,例如

public class cPerson
{
  public int? iID {get;set;}
  public string sName { get; set; }
  public bool? bGoodGuy { get; set; }
}

然后我创建了这个类的实例

cPerson myPerson = new cPerson()

并添加值

myPerson.iID=10;
myPerson.sName="John Smith";
myPerson.bGoodGuy=true;

然后如果我想显示这个人我会做

writeline("Persons id : " + myPerson.iID);
writeLine("Persons name : " + myPerson.sName);
writeLine("Person is good : " + myPerson.bGoodGuy);

但我想要的是根据我的课程中属性定义的顺序写出来

writeline("Persons id : " + myPerson[0]);
writeLine("Persons name : " + myPerson[1]);
writeLine("Person is good : " + myPerson[2]);

这不起作用。

我只是假设这对于某种索引器是可行的,但是我找到的样本是用于索引几个人,例如:

writeLine("Person 0's id is : " + myPerson[0].iID);
writeLine("Person 0's name is : " + myPerson[0].sName);
writeLine("Person 0's good or bad status is : " + myPerson[0].bGoodGuy);

但这不是后来的事。

有些人(C#)足够敏锐,能给我一些方向,我非常感激。

此致

瑞典人

1 个答案:

答案 0 :(得分:1)

首先,这似乎是个坏主意。如果你发现自己真的需要这个,你应该仔细考虑设计方案。

其次,不清楚您是否可以按声明顺序获取属性 - 我会强烈考虑更明确的排序,例如按字母顺序排列。

如果真的想要这样做,你可以添加这样的索引器:

public object this[int index]
{
    get
    {
        // Alternative: remove the hard-coding, and fetch the properties
        // via reflection.
        switch(index)
        {
            // Note: property names changed to conform to .NET conventions
            case 0: return Id;
            case 1: return Name;
            case 2: return GoodGuy;
            default: throw new ArgumentOutOfRangeException("index");
        }
    }
}

......但正如我所说,我不会这样做。

另一种方法是使用Properties属性或方法创建IEnumerable<object>,可能是通过反射。例如:

public IEnumerable<object> Properties()
{
    return typeof(Person).GetProperties()
                         .OrderBy(p => p.Name)
                         .Select(p => p.GetValue(this, null));
}

然后你可以使用:

Console.WriteLine("Persons id : " + myPerson.Properties().ElementAt(0));

此外,如果确实想要,您可以将此作为任何对象的扩展方法。尽管如此,我还是要小心这一点。