How to cast Object to its actual type?

前端 未结 10 1033
余生分开走
余生分开走 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:33

    If you know the actual type, then just:

    SomeType typed = (SomeType)obj;
    typed.MyFunction();
    

    If you don't know the actual type, then: not really, no. You would have to instead use one of:

    • reflection
    • implementing a well-known interface
    • dynamic

    For example:

    // reflection
    obj.GetType().GetMethod("MyFunction").Invoke(obj, null);
    
    // interface
    IFoo foo = (IFoo)obj; // where SomeType : IFoo and IFoo declares MyFunction
    foo.MyFunction();
    
    // dynamic
    dynamic d = obj;
    d.MyFunction();
    
    0 讨论(0)
  • 2020-11-30 20:34

    Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :

    (abc)(obj)).MyFunction();
    

    if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.

    0 讨论(0)
  • 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>(foo);
    result.Bar.ShouldEqual(5);
    result.Baz.ShouldEqual(6);
    
    dynamic foo2 = Mapper.Map<MyDynamicObject>(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

    0 讨论(0)
  • 2020-11-30 20:40
    Implement an interface to call your function in your method
    interface IMyInterface
    {
     void MyinterfaceMethod();
    }
    
    IMyInterface MyObj = obj as IMyInterface;
    if ( MyObj != null)
    {
    MyMethod(IMyInterface MyObj );
    }
    
    0 讨论(0)
提交回复
热议问题