Cannot implicitly convert type 'Int' to 'T'

前端 未结 9 2262
甜味超标
甜味超标 2020-11-27 14:15

I can call Get(Stat); or Get(Name);

But when compiling I get:

Cannot implicitly convert typ

相关标签:
9条回答
  • 2020-11-27 14:54

    ChangeType is probably your best option. My solution is similar to the one provided by BrokenGlass with a bit of try catch logic.

    static void Main(string[] args)
    {
        object number = "1";
        bool hasConverted;
        var convertedValue = DoConvert<int>(number, out hasConverted);
    
        Console.WriteLine(hasConverted);
        Console.WriteLine(convertedValue);
    }
    
    public static TConvertType DoConvert<TConvertType>(object convertValue, out bool hasConverted)
    {
        hasConverted = false;
        var converted = default(TConvertType);
        try
        {
            converted = (TConvertType) 
                Convert.ChangeType(convertValue, typeof(TConvertType));
            hasConverted = true;
        }
        catch (InvalidCastException)
        {
        }
        catch (ArgumentNullException)
        {
        }
        catch (FormatException)
        {
        }
        catch (OverflowException)
        {
        }
    
        return converted;
    }
    
    0 讨论(0)
  • 2020-11-27 14:55
    public T Get<T>(Stats type ) where T : IConvertible
    {
        if (typeof(T) == typeof(int))
        {
            int t = Convert.ToInt16(PlayerStats[type]);
            return (T)t;
        }
        if (typeof(T) == typeof(string))
        {
            string t = PlayerStats[type].ToString();
            return (T)t;
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:55

    Considering @BrokenGlass logic (Convert.ChangeType) does not support for GUID type.

    public T Get<T>(Stats type) where T : IConvertible
    {
        return (T) Convert.ChangeType(PlayerStats[type], typeof(T));
    }
    

    Error: Invalid cast from 'System.String' to 'System.Guid'.

    Instead, use below logic using TypeDescriptor.GetConverter by adding System.ComponentModel namespace.

    public T Get<T>(Stats type) where T : IConvertible
    {
        (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromInvariantString(PlayerStats[type])
    }
    

    Read this.

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