簡體   English   中英

在 c#.Net 中創建基於索引的 Class

[英]Create an Index Based Class in c# .Net

我有一些類,想使用索引或類似的東西訪問它們的屬性

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

而不是這個

ClassObj.PropName.

謝謝

您需要索引器:

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以便基於文字字符串名稱訪問成員。

你可以做這樣的事情,一個偽代碼

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

請注意,這不是完整的解決方案,因為如果您想要擁有非公共屬性/字段、static 等,則需要在反射訪問期間“玩”BindingFlags。

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

這將為您提供索引屬性。 你可以設置任何你想要的參數。

在這里如何使用索引器和您正在尋找的示例。

我不確定你在這里的意思是什么,但我會說你必須讓ClassObject某種IEnumirable類型,比如List<>Dictionary<>才能使用它來瞄准這里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM