C# ‘dynamic’ cannot access properties from anonymous types declared in another assembly

后端 未结 8 2501
无人共我
无人共我 2020-11-27 16:22

Code below is working well as long as I have class ClassSameAssembly in same assembly as class Program. But when I move class ClassSameAssemb

8条回答
  •  [愿得一人]
    2020-11-27 17:05

    ToExpando extension method (mentioned in Jon's answer) for the brave ones

    public static class ExtensionMethods
    {
        public static ExpandoObject ToExpando(this object obj)
        {
            IDictionary expando = new ExpandoObject();
            foreach (PropertyDescriptor propertyDescriptor in TypeDescriptor.GetProperties(obj))
            {
                var value = propertyDescriptor.GetValue(obj);
                expando.Add(propertyDescriptor.Name, value == null || new[]
                {
                    typeof (Enum),
                    typeof (String),
                    typeof (Char),
                    typeof (Guid),
                    typeof (Boolean),
                    typeof (Byte),
                    typeof (Int16),
                    typeof (Int32),
                    typeof (Int64),
                    typeof (Single),
                    typeof (Double),
                    typeof (Decimal),
                    typeof (SByte),
                    typeof (UInt16),
                    typeof (UInt32),
                    typeof (UInt64),
                    typeof (DateTime),
                    typeof (DateTimeOffset),
                    typeof (TimeSpan),
                }.Any(oo => oo.IsInstanceOfType(value))
                    ? value
                    : value.ToExpando());
            }
    
            return (ExpandoObject)expando;
        }
    }
    

提交回复
热议问题