How to cast Object to its actual type?

前端 未结 10 1070
余生分开走
余生分开走 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(Object obj) =>
        JsonConvert.DeserializeObject(obj.ToString());
    

提交回复
热议问题