Cannot implicitly convert type 'Int' to 'T'

前端 未结 9 2263
甜味超标
甜味超标 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: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()
        {
            if(typeof(T) == typeof(bool)) {
                return (T)(object)true;
            }
    
            return default(T);
        }
    
        public static void Main()
        {
            bool boolValue = Foo(); // == true
            string stringValue = Foo(); // == 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.

提交回复
热议问题