有没有办法将JSON内容反序列化为C#4动态类型?为了使用DataContractJsonSerializer,跳过创建一堆类会很不错.
我需要从.NET 4中使用dynamic关键字声明的对象中获取属性及其值的字典?似乎使用反射这是行不通的.
例:
dynamic s = new ExpandoObject();
s.Path = "/Home";
s.Name = "Home";
// How do I enumerate the Path and Name properties and get their values?
IDictionary<string, object> propertyValues = ???
我正在尝试理解DynamicObject类型.发现这篇MSDN文章非常简洁明了,如何创建和使用DynamicObject:
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
本文包含一个继承自DynamicObject的简单DynamicDictionary类.
现在我想迭代我动态创建的DynamicObject属性:
dynamic d = new DynamicDictionary();
d.Name = "Myname";
d.Number = 1080;
foreach (var prop in d.GetType().GetProperties())
{
  Console.Write prop.Key;
  Console.Write prop.Value;
}
显然这不起作用.我想学习如何在不改变DynamicDictionary类的情况下做到这一点,因为我真的想学习如何将它用于从DynamicObject继承的各种现有对象.
需要反思吗?我肯定错过了什么...
我正在实现一个通用函数来从任意提供的动态对象中提取值,但不知道如何调用,TryGetMember因为它需要一个GetMemberBinder抽象的,因此我无法创建它.样品...
public object GetValue(DynamicObject Source, string FieldName)
{
    object Result = null;
    GetMemberBinder Binder = x;  // What object must be provided?
    Binder.Name = FieldName;
    if (Source.TryGetMember(Binder, out Result))
       return Result;
    throw new Exception("The field '" + FieldName + "' not exists");
}
是否已经存在GetMemberBinder已经存在的具体后代?或者是创建我自己的实现的指南?
我使用反射来获取 type 的返回值object,但它的实际类型是(int[], string[])我仔细检查obj.GetType().ToString()并打印的System.ValueTuple`2[System.Int32[],System.String[]]。
但只是用((int[], string[]))obj或(ValueTuple<int[],string[]>)objreturn 进行强制转换,则强制转换无效。如何正确地做到这一点?
我知道这个主题在stackoverflow上有很多问题,但我找不到任何具体的答案来解决我目前的情况.
Run Code Online (Sandbox Code Playgroud)// collection gets populated at run time, the type T is dynamic. public void GenerateExcel<T>(string filename, IEnumerable<T> collection) { // Since the T passed is dynamic Type I am facing issues in getting // the property names. var type = typeof(T); // the type T is an anonymous type, and thus // the 'type' variable is always an Object type. var columns = type.GetProperties().Length; // when I run this line it // is obvious the properties …