开发者

C# Absolute Value for dynamic type

开发者 https://www.devze.com 2022-12-16 15:45 出处:网络
I have code that computes the absolute value of a custom value type: public Angle Abs(Angle agl) { return (360 - Angle.Degrees);

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);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号