C# Generic method return values

后端 未结 4 1892
不知归路
不知归路 2021-01-02 00:32

I\'m just learning about generics and have a question regarding method return values.

Say, I want a generic method in the sense that the required generic part of the

相关标签:
4条回答
  • 2021-01-02 00:49

    You could do something like ...

       public TResult Parse<TResult>(string parameter)
        {
         /* do stuff */
        }
    

    And use it like ...

    int result = Parse<int>("111");
    

    And then it will depend on your implementation in the Parse method.

    Hope it helps.

    0 讨论(0)
  • 2021-01-02 01:03

    Something like this?

    void Main()
    {
        int iIntVal = ConvertTo<int>("10");
        double dDoubleVal = ConvertTo<double>("10.42");
    }
    
    public T ConvertTo<T>(string val) where T: struct
    {
        return (T) System.Convert.ChangeType(val, Type.GetTypeCode(typeof(T)));
    }
    
    0 讨论(0)
  • 2021-01-02 01:04

    Yes it's possible.

    Example:

    public T ParseValue<T>(String value) { 
        // ...
    }
    
    0 讨论(0)
  • 2021-01-02 01:11

    You cannot return either a double or an int from a generic method without it also returning any other type.

    I might, for example, have a Foo class and your generic parse method, without any constraint, will allow this call to be made:

    Foo result = Parse<Foo>("111");
    

    The best that you can do with numbers is constrain on your function by only allowing struct (value-types) to be used.

    T Parse<T>(string value) where T : struct;
    

    But this will allow all number types, plus any other value-type.

    You can constrain by interface type, but there isn't an INumeric interface on double or int so you're kind of stuck.

    The only thing that you can do is throw an exception if the wrong type is passed in - which generally isn't very satisfying.

    Your best approach, in this case, is to abandon generics and use separately named methods.

    double ParseDouble(string value);
    int ParseInteger(string value);
    

    But, of course, this won't help you learn generics. Sorry.

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