在c#.Net中创建基于索引的类

时间:2011-08-17 09:06:14

标签: c# .net oop

我有一些类,并希望使用索引或类似

访问其属性

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

而不是

ClassObj.PropName.

谢谢

5 个答案:

答案 0 :(得分:8)

您需要索引器:

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();

这是记事本编码,所以请用一点盐,但索引器语法是正确的。

如果您想使用它以便动态访问属性,那么您的索引器可以使用Reflection将密钥名称作为属性名称。

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

答案 1 :(得分:7)

您可以执行以下操作:伪代码

    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。

答案 2 :(得分:0)

public string this[int index] 
 {
    get 
    { ... }
    set
    { ... }
 }

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

答案 3 :(得分:0)

Here如何使用您要查找的索引器和示例。

答案 4 :(得分:0)

我不确定您的意思,但我要说您必须ClassObject某种IEnumirable类型,例如List<>或{ {1}}以此为目标使用它。