C# Absolute Value for dynamic type
I have code that computes the absolute value of a custom value type:
public Angle Abs(Angle agl)
{
return (360 - Angle.Degrees);
}
This isn't my actual application but it will serve my point. Then I have a method like so:
public dynamic 开发者_JS百科DoStuff(Foo f)
{
// f contains a list of value types: int, double, decimal, angle
return Abs(f[0]);
}
public dynamic this[int intIndex] // Within class Foo
{
get { return Items[intIndex]; }
}
My question is this: in the function DoStuff() how do I overload the Abs() function to accept the normal value types using System.Math.Abs(), but also accept the type of Angle?
C# 4.0 supported answers are available.
I'm willing to have a separate function; something like this [assuming it would actually work]:
public dynamic Abs(dynamic dyn)
{
if (dyn.GetType() = typeof(Angle))
{
return Abs(dyn);
}
else
{
return System.Math.Abs(dyn);
}
}
Separate functions, no need to call GetType. This behavior wholly depends on the fact that F[] is of type "dynamic".
public Angle Abs(Angle agl)
{
return (360 - Angle.Degrees);
}
public dynamic Abs(dynamic n)
{
return Math.Abs(n);
}
Abs(F[0])
public dynamic Abs(dynamic dyn)
{
if (dyn.GetType() = typeof(Angle))
{
return Abs(dyn);
}
else
{
return System.Math.Abs(dyn);
}
}
精彩评论