与普遍的看法相反,这是可以做到的,但涉及到一些丑陋的 hack,这将导致以后的维护问题。它涉及编写一个类来将您的匿名对象“包装”成一个动态对象。前段时间我把它作为一个练习,下面是包装类的代码,你可以像ViewBag.Stuff = new DynamicAnonymous(new { Name = "Test", Email = "user@domain.com" });
..一样使用它
public class DynamicAnonymous : DynamicObject
{
object obj;
public DynamicAnonymous(object o)
{
this.obj = o;
}
public override IEnumerable<string> GetDynamicMemberNames()
{
return obj.GetType().GetProperties().Select(n => n.Name);
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var prop = obj.GetType().GetProperty(binder.Name);
if (prop == null)
{
result = null;
return false;
}
else
{
result = prop.GetValue(obj, null);
return true;
}
}
public override int GetHashCode()
{
return obj.GetHashCode();
}
public override string ToString()
{
return obj.ToString();
}
public override bool Equals(object obj2)
{
return obj.Equals(obj2);
}
}