MSDN 說明
The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember")C# Code
using System.Dynamic;
using System.ComponentModel;
namespace Basic
{
class Program
{
static void Main(string[] args)
{
dynamic sampleObject = new ExpandoObject();
// 動態新增 Property
sampleObject.Property = "Dynamic Property";
Console.WriteLine("----- 動態新增 Property -----");
Console.WriteLine($"Type:{sampleObject.Property.GetType()} - Property Value:{sampleObject.Property}");
// 動態新增 Method
sampleObject.number = 10;
sampleObject.Increment = (Action)(() => { sampleObject.number++; });
Console.WriteLine("----- 動態新增 Method -----");
Console.WriteLine($"原值:{sampleObject.number}");
sampleObject.Increment();
Console.WriteLine($"增值:{sampleObject.number}");
// 動態新增 Event
sampleObject.sampleEvent = null;
Console.WriteLine("----- 動態新增 Event -----");
sampleObject.sampleEvent += new Action<object, EventArgs>((sender, e) =>
{
Console.WriteLine($"SampleHandler for {sender} event");
});
sampleObject.sampleEvent(sampleObject, new EventArgs());
// 參數傳遞
dynamic employee, manager;
employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
manager = new ExpandoObject();
manager.Name = "Allison Brown";
manager.Age = 42;
manager.TeamSize = 10;
WritePerson(manager);
WritePerson(employee);
// 移除 Name Property
((IDictionary<String, Object>)employee).Remove("Name");
Console.WriteLine("----- 移除 Name Property -----");
foreach (var property in (IDictionary<String, Object>)employee)
{
Console.WriteLine($"{property.Key} : {property.Value}");
}
// PropertyChanged Event
((INotifyPropertyChanged)employee).PropertyChanged += ((sender, e) =>
{
Console.WriteLine($"{e.PropertyName} has changed.");
});
Console.WriteLine("----- PropertyChanged Event -----");
employee.Name = "John Smith";
}
static void WritePerson(dynamic person)
{
try
{
Console.WriteLine($"{person.Name} is {person.Age} years old in Team {person.TeamSize}.");
}
catch (Exception ex)
{
Console.WriteLine($"{person.Name}:{ex.Message}");
}
}
}
}
沒有留言:
張貼留言