C# Generic method return values

后端 未结 4 1931
不知归路
不知归路 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 01:03

    Something like this?

    void Main()
    {
        int iIntVal = ConvertTo("10");
        double dDoubleVal = ConvertTo("10.42");
    }
    
    public T ConvertTo(string val) where T: struct
    {
        return (T) System.Convert.ChangeType(val, Type.GetTypeCode(typeof(T)));
    }
    

提交回复
热议问题