How to cast Object to its actual type?

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

    This method might not be the most efficient but is simple and does the job.

    It performs two operations: firstly it calls .ToString() which is basiclly a serialization, and then the deserialization using Newtonsoft nuget (which you must install).

    public T Format<T>(Object obj) =>
        JsonConvert.DeserializeObject<T>(obj.ToString());
    
    0 讨论(0)
  • 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;
            ...
        }
    }
    
    0 讨论(0)
  • 2020-11-30 20:18

    If your MyFunction() method is defined only in one class (and its descendants), try

    void MyMethod(Object obj) 
    {
        var o = obj as MyClass;
        if (o != null)
            o.MyFunction();
    }
    

    If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:

    interface IMyInterface
    {
        void MyFunction();
    }
    
    void MyMethod(Object obj) 
    {
        var o = obj as IMyInterface;
        if (o != null)
            o.MyFunction();
    }
    
    0 讨论(0)
  • 2020-11-30 20:19

    How about JsonConvert.DeserializeObject(object.ToString());

    0 讨论(0)
  • 2020-11-30 20:23

    Casting to actual type is easy:

    void MyMethod(Object obj) {
        ActualType actualyType = (ActualType)obj;
    }
    
    0 讨论(0)
  • 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<T>(object obj) {
        (T)obj.ThatClassMethodYouWantedToInvoke();
    }
    
    // Meanwhile, where the method is called:
    TheObliviousHelperMethod<ActualType>(obj);
    

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

    0 讨论(0)
提交回复
热议问题