I am implementing the next function:
private bool CheckRelativeIncrease(T pVal1, T pVal2, out T pFluctuation, int x)
where I compare if pVal2 has increased more than a "x%" over pVal1. I am using Gen开发者_StackOverflow中文版erics to make the function work with int, short... I am using MiscUtils.Operator but the problem is that I can't mix known and unknown types. The following code doesn't work:
bool increased = false;
int comparer = Comparer.Default.Compare(pVal1, pVal2);
pFluctuation = Operator<T>.Zero;
if (comparer > 0) {
int factor = (int)(1 + (x / 100));
pFluctuation = Operator.Multiply(factor, pVal2);
comparer = Comparer.Default.Compare(pVal1, pFluctuation);
if (comparer >= 0)
increased = true;
}
return increased;
"Operator.Multiply" gives me an error because 'factor' has not the same type as 'pVal2'.
Any ideas?
Thanks in advance, Silvia
I don't believe we currently support operators on mixed types - but if you look at the code in Operator<T>
it should be pretty easy to adapt it. Feel free to send me a patch :)
Basically you'll need an Operator<T1, T2, TResult>
which looks like Operator<TValue, TResult>
except it uses different types for the different inputs and outputs. You'll need to specify what the expected result type is, of course - if you're multiply T
by int
, would you expect the result to be int
, T
or something else?
If you're using C# 4 and .NET 4, you may want to consider using dynamic typing instead...
There is also two-type multiply operation which you can use, according to this documentation:
public static TArg1 MultiplyAlternative(TArg1 value1, TArg2 value2)
Write another function to cast one type as another type. Make a nested call to that function within your code and problem solved.
精彩评论