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

本文关键字:于索引 索引 一个 Net 创建 | 更新日期: 2023-09-27 18:05:44

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

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

而不是这个

ClassObj.PropName.

感谢

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

您需要索引器:

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,以便基于文字字符串名称访问成员。

您可以这样做,一个伪代码:

    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。

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

这将为您提供一个索引属性。您可以根据需要设置任何参数。

我不知道你在这里是什么意思,但我要说的是,你必须使ClassObject成为某种IEnumirable类型,比如List<>Dictionary<>,才能在这里使用它。