How to cast Object to its actual type?

前端 未结 10 1059
余生分开走
余生分开走 2020-11-30 19:46

If I have:

void MyMethod(Object obj) {   ...   }

How can I cast obj to what its actual type is?

10条回答
  •  时光取名叫无心
    2020-11-30 20:38

    In my case AutoMapper works well.

    AutoMapper can map to/from dynamic objects without any explicit configuration:

    public class Foo {
        public int Bar { get; set; }
        public int Baz { get; set; }
    }
    dynamic foo = new MyDynamicObject();
    foo.Bar = 5;
    foo.Baz = 6;
    
    Mapper.Initialize(cfg => {});
    
    var result = Mapper.Map(foo);
    result.Bar.ShouldEqual(5);
    result.Baz.ShouldEqual(6);
    
    dynamic foo2 = Mapper.Map(result);
    foo2.Bar.ShouldEqual(5);
    foo2.Baz.ShouldEqual(6);
    

    Similarly you can map straight from dictionaries to objects, AutoMapper will line up the keys with property names.

    more info https://github.com/AutoMapper/AutoMapper/wiki/Dynamic-and-ExpandoObject-Mapping

提交回复
热议问题