C# 支援 dynamic,你可以建立System.Dynamic.ExpandoObject物件,可動態新增、移除成員。成員包含屬性、方法、事件等。
例如以下動態建立一個ExpandoObject物件,新增EmpID 、EmpName 與Age 三個屬性,並新增一個Print 方法:
dynamic emp = new System.Dynamic.ExpandoObject( );
emp.EmpID = 1;
emp.EmpName = "Mary";
emp.Age = 25;
emp.Print = (Action) ( ( ) => {
Console.WriteLine(
emp.EmpID.ToString( ) + "," +
emp.EmpName + "," +
emp.Age.ToString( ));
}
);
Console.WriteLine( emp.EmpID);
Console.WriteLine( emp.EmpName);
Console.WriteLine( emp.Age);
emp.Print( );
emp.EmpID = 1;
emp.EmpName = "Mary";
emp.Age = 25;
emp.Print = (Action) ( ( ) => {
Console.WriteLine(
emp.EmpID.ToString( ) + "," +
emp.EmpName + "," +
emp.Age.ToString( ));
}
);
Console.WriteLine( emp.EmpID);
Console.WriteLine( emp.EmpName);
Console.WriteLine( emp.Age);
emp.Print( );
若要移除其成員,可以使用Remove方法,例如以下移除Age:
( (IDictionary<String , Object>) emp ).Remove( "Age" );
在Visual Studio 2012中斷模式檢視時,Age已移除:
沒有留言:
張貼留言