我在C#中有一个dynamic
对象,我想转换为静态对象。我写了一个函数,它接受动态类型并返回静态类型,但它实际返回dynamic
,忽略指定的返回类型。 (这是标准行为,正如我现在发现的那样。)AutoMapper不处理dynamic
类型。如何正确地将dynamic
转换为静态?
答案 0 :(得分:3)
使用某些序列化程序可以解决问题。假设您形成一个动态对象,如
dynamic d = new ExpandoObject();
d.a = 1;
d.b = new ExpandoObject();
d.b.c = "222";
并且您希望将其转换为A
public class A
{
public int a { set; get; }
public B b { set; get; }
}
public class B
{
public string c { set; get; }
}
您可以使用Json.Net来执行此序列化/反序列化
A a = JsonConvert.DeserializeObject<A>(JsonConvert.SerializeObject(d));
答案 1 :(得分:0)
如果您获得了类型,则可以实例化一个新对象,然后使用FormatterServices类将动态对象的状态复制到此对象中:
var staticObject = Activator.CreateInstance(yourType);
MemberInfo[] members = FormatterServices.GetSerializableMembers(yourType);
FormatterServices.PopulateObjectMembers(staticObject, members,
FormatterServices.GetObjectData(dynObject, members));
答案 2 :(得分:-3)
我很困惑......我认为.NET应该已经为你做了这件事。这是一些测试代码,符合我的期望:
class Program
{
static void Main(string[] args)
{
dynamic anythingGoes = 1;
var convertedToInt = ConvertToType<int>(anythingGoes);
// expectation: should output Int32. and it does....
Console.WriteLine(convertedToInt.GetType().Name);
anythingGoes = "ribbit";
var convertedToString = ConvertToType<string>(anythingGoes);
// expectation: should output String. and it does also...
Console.WriteLine(convertedToString.GetType().Name);
Console.ReadLine();
}
// just a small method to cast the dynamic to whatever i want
// ...only for this test. not guaranteed to be crash safe. in fact, don't assume!
static T ConvertToType<T>(dynamic obj)
{
T result = obj;
return result;
}
}