Cannot implicitly convert type 'Int' to 'T'

前端 未结 9 2261
甜味超标
甜味超标 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:29

    It looks like you need a TypeConverter, see this blog entry.

    0 讨论(0)
  • 2020-11-27 14:36

    You should be able to just use Convert.ChangeType() instead of your custom code:

    public T Get<T>(Stats type) where T : IConvertible
    {
        return (T) Convert.ChangeType(PlayerStats[type], typeof(T));
    }
    
    0 讨论(0)
  • 2020-11-27 14:38

    Try this:

    public T Get<T>(Stats type ) where T : IConvertible
    {
        if (typeof(T) == typeof(int))
        {
            return (T)(object)Convert.ToInt16(PlayerStats[type]);
    
        }
        if (typeof(T) == typeof(string))
        {
    
            return (T)(object)PlayerStats[type];
        }
    }
    
    0 讨论(0)
  • 2020-11-27 14:38

    Actually, you can just convert it to object and then to T.

    T var = (T)(object)42;

    An example for bool:

    public class Program
    {
        public static T Foo<T>()
        {
            if(typeof(T) == typeof(bool)) {
                return (T)(object)true;
            }
    
            return default(T);
        }
    
        public static void Main()
        {
            bool boolValue = Foo<bool>(); // == true
            string stringValue = Foo<string>(); // == null
        }
    }
    

    Sometimes, this behavior is desirable. For instance, when implementing or overriding a generic method from a base class or interface and you want to add some different functionalities based on the T type.

    0 讨论(0)
  • 2020-11-27 14:39

    You can simply cast like below,

    public T Get<T>(Stats type) where T : IConvertible
    {
      if (typeof(T) == typeof(int))
      {
        int t = Convert.ToInt16(PlayerStats[type]);
        return t as T;
      }
     if (typeof(T) == typeof(string))
     {
        string t = PlayerStats[type].ToString();
        return t as T;
     }
    }
    
    0 讨论(0)
  • 2020-11-27 14:51

    Any time you find yourself switching on a type in a generic you are almost certainly doing something wrong. Generics should be generic; they should operate identically completely independent of the type.

    If T can only be int or string then don't write your code this way at all in the first place. Write two methods, one that returns an int and one that returns a string.

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