How to cast Object to its actual type?

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

    If multiple types are possible, the method itself does not know the type to cast, but the caller does, you might use something like this:

    void TheObliviousHelperMethod(object obj) {
        (T)obj.ThatClassMethodYouWantedToInvoke();
    }
    
    // Meanwhile, where the method is called:
    TheObliviousHelperMethod(obj);
    

    Restrictions on the type could be added using the where keyword after the parentheses.

提交回复
热议问题