推荐使用ExpandoObject 创建动态对象
using System;
using System.Collections.Generic;
using System.Dynamic;
namespace DynamicTest
{
class Program
{
//创建动态对象,有两种方法:
//1)从DynamicObject中派生,使用它需要做的工作较多,必须重写几个方法
//2)直接使用ExpandoObject,是一个可立即使用的密封类
static void Main(string[] args)
{
dynamic expObject = new ExpandoObject();
expObject.FirstName = "henry1";
expObject.LastName = "henry2";
Console.WriteLine(expObject.FirstName + " " + expObject.LastName);
Func<DateTime, string> GetTomorrow = today => today.AddDays(1).ToShortDateString();
expObject.GetTomorrowDate = GetTomorrow;
Console.WriteLine("Tomorrow is {0}", expObject.GetTomorrowDate(DateTime.Now));
expObject.Friends = new List<Person>();
expObject.Friends.Add(new Person() { FirstName = "test1", LastName = "test11" });
expObject.Friends.Add(new Person() { FirstName = "test2", LastName = "test22" });
foreach (Person friend in expObject.Friends)
{
Console.WriteLine(friend.FirstName + " " + friend.LastName);
}
Console.ReadLine();
}
}
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string GetFullName()
{
return string.Concat(FirstName, " ", LastName);
}
}
}