Generic method to type casting

前端 未结 8 1119
不思量自难忘°
不思量自难忘° 2021-02-02 11:55

I\'m trying to write generic method to cast types. I want write something like Cast.To(variable) instead of (Type) variable. My wrong versi

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-02 12:19

    You can do this trick by finding the right methods through Reflection:

    public static T To (object obj)
    {
        Type sourceType = obj.GetType ();
        MethodInfo op = sourceType.GetMethods ()
                        .Where (m => m.ReturnType == typeof (T))
                        .Where (m => m.Name == "op_Implicit" || m.Name == "op_Explicit")
                        .FirstOrDefault();
    
        return (op != null)
            ? (T) op.Invoke (null, new [] { obj })
            : (T) Convert.ChangeType (obj, typeof (T));
    }
    

    In .NET 4.0, you can use dynamic keyword as suggested in other answers.

提交回复
热议问题