Cannot implicitly convert type 'T' to 'Int'

后端 未结 6 1780
轻奢々
轻奢々 2020-12-16 14:38

When trying to call this function in my code i get the error in the title. Also Operator \'+=\' cannot be applied to the operands of type \'int\' and \'T\'

p         


        
相关标签:
6条回答
  • 2020-12-16 15:03

    It knows not how to add your T to a numeric since it doesnt know what the type of T is going to be.

    t += Convert.ToInt32(value);
    

    But since you are adding int to int and returning int then why not just ditch the generic parameter and make it

    public int Change(Stats type, int value)  
    

    and if you want different behaviour for different types and really want the same method name, instead of testing the type just do:

     public int Change(Stats type, string value) 
     public int Change(Stats type, DateTime value)  
    
    0 讨论(0)
  • 2020-12-16 15:05

    I had a very similar problem. It is not exactly the problem asked here, but it could be a start point:

        private T GetXValue<T>(XElement xElem, string name)
        {
            try
            {
                object o = xElem.Element(name).Value;
                return (T)Convert.ChangeType(o, typeof(T));
            }
            catch 
            {
                return (T)Activator.CreateInstance(typeof(T), null);
            }
        }
    
    0 讨论(0)
  • 2020-12-16 15:13

    you can try casting the value like this ...

    t += (int)value; 
    

    or

    t+= Convert.ToInt32(value);
    
    0 讨论(0)
  • 2020-12-16 15:15

    The error you are getting makes sence. While you call the method with int as the type, the compiler doesn't know that will be the case.

    To compile the method as it is, the compiler will need to prove that the operations you do on T will be valid for all T - which is clearly not the case.

    0 讨论(0)
  • 2020-12-16 15:23

    You can set constraint:

    public int Change<T>(Stats type, T value) where T : IConvertible
    

    Then:

    var intValue = value.ToInt32();
    
    0 讨论(0)
  • 2020-12-16 15:26

    Or another way (object cast is necessary not typo)

    t += (int)(object)value;

    Or use dynamic, by using dynamic you can do more, such as implicit casts

    Or use Int32 - Int32 and int are both struct internally. No performance loss

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