How to cast Object to its actual type?

前端 未结 10 1071
余生分开走
余生分开走 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();
    

提交回复
热议问题