How to cast Object to its actual type?

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

    I don't think you can (not without reflection), you should provide a type to your function as well:

    void MyMethod(Object obj, Type t)
    {
        var convertedObject = Convert.ChangeType(obj, t);
        ...
    }
    

    UPD:

    This may work for you:

    void MyMethod(Object obj)
    {
        if (obj is A)
        {
            A a = obj as A;
            ...
        } 
        else if (obj is B)
        {
            B b = obj as B;
            ...
        }
    }
    

提交回复
热议问题