How to create extension methods for Types

前端 未结 4 1782
名媛妹妹
名媛妹妹 2020-12-20 11:13

I am writing an extension method for parsing JSON string for any given type. I wanted to use the method on types instead of instances like many examples we already know, but

相关标签:
4条回答
  • 2020-12-20 11:52

    To use the extension method, you would have to do:

    var instance = typeof(MyClass).ParseJson(text);
    

    The token "MyClass" is not a Type instamce intself, but using typeof will get you a Type to operate on. But how is this any better than:

    var instance = JsonUtility.ParseJson<MyClass>(text);
    

    Edit: Actually, the code for the extension method still would not do what you wanted. It will always return a "Type" object, not an instance of that Type.

    0 讨论(0)
  • 2020-12-20 11:52

    You can't create extension methods that apply to the type itself. They can only be called on instances of a type.

    0 讨论(0)
  • 2020-12-20 12:03

    As stated in the accepted answer, you can't. However, provided that you have an extension method that can be called from an instance of T:

    public static T ParseJson<T>(this T t, string s)
    

    You could write a utility method like this:

    public static T ParseJson<T>(string s)
        where T: new()
        => new(T).ParseJson(s);
    

    And call it like this:

    var t = Utilities.ParseJson<T>(s);
    

    I am afraid that's the best you can do...

    0 讨论(0)
  • 2020-12-20 12:05

    The short answer is it cannot be done; extension methods need to work on an instance of something.

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