📌  相关文章
📜  c# expandoobject indexer - C# (1)

📅  最后修改于: 2023-12-03 15:13:48.895000             🧑  作者: Mango

C# ExpandoObject Indexer

The ExpandoObject class in C# allows you to create dynamic objects, whose members can be added and removed at runtime. One of the important features of ExpandoObject is its ability to use indexers.

Indexers in C#

Indexers are like properties, but they allow you to access the object's elements using an index. They are commonly used to access elements in an array, list, or dictionary. Here is an example of a simple indexer in C#:

public class MyObject
{
    private int[] values = new int[10];

    public int this[int index]
    {
        get { return values[index]; }
        set { values[index] = value; }
    }
}

In this example, MyObject has an indexer that allows you to get or set elements in the values array. You can access the elements using the syntax myObject[index], just like you would with an array.

ExpandoObject Indexer

The ExpandoObject class also supports indexers, which allow you to dynamically add and access properties of the object. Here is an example:

dynamic obj = new ExpandoObject();
obj.Name = "John";
obj.Age = 30;
obj["Address"] = "123 Main St.";

Console.WriteLine(obj.Name);
Console.WriteLine(obj["Age"]);
Console.WriteLine(obj.Address);

In this example, we create a new ExpandoObject and add three properties: Name, Age, and Address. We can access each property using either dot notation or the indexer syntax.

It's important to note that using the indexer syntax with ExpandoObject is similar to using a dictionary. You can add or remove properties at runtime, like this:

dynamic obj = new ExpandoObject();
obj.Name = "John";
obj.Age = 30;

obj["Address"] = "123 Main St.";
obj["Phone"] = "555-555-5555";

Console.WriteLine(obj.Phone);

obj["Age"] = 35;
Console.WriteLine(obj.Age);

IDictionary<string, object> dict = obj;
dict.Remove("Phone");

In this example, we first add two properties to the ExpandoObject. Then, we use the indexer syntax to add two more properties: Address and Phone. We can access the Phone property using the indexer syntax, and modify the Age property using dot notation.

Finally, we convert the ExpandoObject to a dictionary and remove the Phone property using the dictionary's Remove method.

Conclusion

The ExpandoObject class in C# allows you to create dynamic objects and use indexers to access their properties. Using indexers with ExpandoObject is similar to using a dictionary, and allows you to add or remove properties at runtime.