简体   繁体   中英

Overloading = operator in C#

OK, I know that it's impossible, but it was the best way to formulate the title of the question. The problem is, I'm trying to use my own custom class instead of float (for deterministic simulation) and I want to the syntax to be as close as possible. So, I certainly want to be able to write something like

FixedPoint myNumber = 0.5f;

Is it possible?

Yes, by creating an implicit type cast operator for FixedPoint if this class was written by you.

class FixedPoint
{
    public static implicit operator FixedPoint(double d)
    {
        return new FixedPoint(d);
    }
}

If it's not obvious to the reader/coder that a double can be converted to FixedPoint , you may also use an explicit type cast instead. You then have to write:

FixedPoint fp = (FixedPoint) 3.5;

Overload implicit cast operator:

class FixedPoint
{
    private readonly float _floatField;

    public FixedPoint(float field)
    {
        _floatField = field;
    }

    public static implicit operator FixedPoint(float f)
    {
        return new FixedPoint(f);
    }

    public static implicit  operator float(FixedPoint fp)
    {
        return fp._floatField;
    }
}

So you can use:

FixedPoint fp = 1;
float f = fp;

Create an implicit type cast.

This is an example:

<class> instance = new <class>();

float f = instance; // We want to cast instance to float.

public static implicit operator <Predefined Data type> (<Class> instance)
{
    //implicit cast logic
    return <Predefined Data type>;
}

If the Implicit is not what you want in = overloading, the other option is to use the explicit operator on your class such as below, which one will cast to it, making it understood by the user:

public static explicit operator FixedPoint(float oc)     
{         

     FixedPoint etc = new FixedPoint();          
     etc._myValue = oc;          
     return etc;      
}

... usage

FixedPoint myNumber = (FixedPoint)0.5f;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM