【问题标题】:Create an Index Based Class in c# .Net在 c# .Net 中创建基于索引的类
【发布时间】:2011-10-28 18:00:26
【问题描述】:

我有一些类,想使用索引或类似的东西访问它们的属性

ClassObject[0] 或更好的是ClassObject["PropName"]

而不是这个

ClassObj.PropName.

谢谢

【问题讨论】:

  • 请显示一些代码...您的属性的类型是什么,请写下您为什么要以这种方式访问​​它们?

标签: c# .net oop


【解决方案1】:

您需要索引器:

http://msdn.microsoft.com/en-us/library/aa288465(v=vs.71).aspx

public class MyClass
{
    private Dictionary<string, object> _innerDictionary = new Dictionary<string, object>();

    public object this[string key]
    {
        get { return _innerDictionary[key]; }
        set { _innerDictionary[key] = value; }
    }
}

// Usage
MyClass c = new MyClass();
c["Something"] = new object();

这是记事本编码,因此请稍加注意,但索引器语法是正确的。

如果您想使用它来动态访问属性,那么您的索引器可以使用反射将键名作为属性名。

或者,查看dynamic 对象,特别是ExpandoObject,可以将其强制转换为IDictionary,以便根据文字字符串名称访问成员。

【讨论】:

    【解决方案2】:

    你可以做这样的事情,一个伪代码

        public class MyClass
        {
    
            public object this[string PropertyName]
            {
                get
                {
                    Type myType = typeof(MyClass);
                    System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
                    return pi.GetValue(this, null); //not indexed property!
                }
                set
                {
                    Type myType = typeof(MyClass);
                    System.Reflection.PropertyInfo pi = myType.GetProperty(PropertyName);
                    pi.SetValue(this, value, null); //not indexed property!
                }
            }
        }
    

    然后像使用它一样

    MyClass cl = new MyClass();
    cl["MyClassProperty"] = "cool";
    

    请注意,这不是完整的解决方案,因为如果您想拥有非公共属性/字段、静态属性等,则需要在反射访问期间“玩”BindingFlags。

    【讨论】:

      【解决方案3】:
      public string this[int index] 
       {
          get 
          { ... }
          set
          { ... }
       }
      

      这将为您提供索引属性。你可以设置任何你想要的参数。

      【讨论】:

        【解决方案4】:

        Here如何使用索引器和你要找的例子。

        【讨论】:

          【解决方案5】:

          我不确定你在这里的意思,但我会说你必须将ClassObject 设为某种IEnumirable 类型,如List&lt;&gt;Dictionary&lt;&gt; 以使用它来瞄准在这里。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-04-03
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-12-07
            • 2021-08-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多