Home > other >  Novice to solve... C # generics how two variables of type T operation for addition, subtraction, mul
Novice to solve... C # generics how two variables of type T operation for addition, subtraction, mul

Time:09-19

Public class IntValue
{
Public int iBase;
Public int iPlus.
Public int iFinal;
Public void updateValue (string operate, bool percent)
{
The switch (operate)
{
The case "+" :
if(! Percent)
IFinal=iPlus iBase +;
The else
IFinal=iPlus iBase + iBase *;
break;
Case "-" :
if(! Percent)
IFinal=iBase - iPlus;
The else
IFinal=iPlus iBase - iBase *;
break;
Default:
The Debug. LogError (" operate error!" );
break;
}
}
}
I want to make three variables are float type, so I want to use generics, but how to get the update of the addition and subtraction is not wrong? Or in a train of thought?

CodePudding user response:

Don't quite understand what you want to do,
If only three variables into a float, under direct definition to cough up,
Public float iBase;
Public float iPlus.
Public float iFinal;

Float and subtract should not go wrong,

CodePudding user response:

Public class IntValue
{
Public T iBase;
Public T iPlus;
Public T iFinal;
}

But unfortunately cannot do limit of T type, can be used, but very see value type, compile time may be wrong,

CodePudding user response:

After the original poster is to consider the code changes, so use generics,
I think so, directly add the where constraints -- where T: struck (any value types can be used as a type argument), later want to change this once the where words,
Have a try,
PS: just learning U3D

CodePudding user response:

Methods 3 floor can, in fact, you can also use instantiate a generic class a try,

CodePudding user response:

3/f positive solution where add a constraint

CodePudding user response:

 private static T Sum Num2 num1 (T, T) where T: struct 
{
The dynamic v1=num1;
The dynamic v2=num2;
Return (T) (v1 + v2);
}

CodePudding user response:

Consider an arbitrary value type of the realization of the accumulator, the code is as follows:
 
T Sum (params T [] Numbers) where T: struct
{
Double total=0;
The foreach (var value in Numbers)
Total=total + Double. Parse (value. The ToString ());
Return (T) Convert. ChangeType (total, typeof (T));
}

Numeric types are summed up because only, so the data type of the accumulator is set to the largest range of type double, further should increase also judge whether T is part of the value type, in order to enhance the robustness of the code!