【问题标题】:C# class attributes, get them by indexC#类属性,通过索引获取
【发布时间】:2013-04-09 18:05:48
【问题描述】:

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

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

【问题讨论】:

  • 它们不是属性,而是属性。要通过索引获取它们,您必须使用 Reflection,伪代码为:string birthNo = (string)p.GetType().GetProperties()[0].GetValue(p, null);.
  • 否;你为什么要?我怀疑有一种更好的方法来做你想做的事情,它不涉及按索引访问属性。
  • @Adriano 你应该把你的评论作为答案
  • @voo 懒得做它并用适当的例子和解释来扩展它...... :)
  • @Adriano 最好不要使用它:“GetProperties 方法不会以特定顺序返回属性,例如字母顺序或声明顺序。您的代码不得依赖于返回属性的顺序,因为顺序不同。”来自msdn.microsoft.com/en-us/library/aky14axb.aspx 的文档

标签: c# class attributes indexing


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你可以在你的 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];
    

    这非常混乱,我想不出你为什么要这样做,但无论如何这是一个答案! :)

    【讨论】:

    • 如果我是写这门课的人就足够了。我没有,我只是在使用它。使用 foreach (Person p in personList) { PropertyInfo[] properties = p.GetType().GetProperties(); 遍历对象后foreach(personProperties 中的PropertyInfo 项){...我得到的是 item.name,在我的例子中是 BirthNo。我想要这个人birthno 的值,并且由于p.item.name 无法使用,我希望使用索引。不过感谢您的回复:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-01
    • 1970-01-01
    • 2016-05-09
    • 2012-03-23
    相关资源
    最近更新 更多