简体   繁体   English

在C#中重载=运算符

[英]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. 是的,如果此类是由您编写的,则通过为FixedPoint创建隐式类型转换运算符。

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. 如果读者/编码器不明显double FixedPoint可以转换为FixedPoint ,您也可以使用显式类型转换。 You then have to write: 然后你必须写:

FixedPoint fp = (FixedPoint) 3.5;

Overload implicit cast operator: 重载implicit运算符:

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: 如果Implicit不是你想要的=重载,另一个选择是在你的类上使用显式运算符,如下面的那个,将被强制转换给它,让用户理解:

public static explicit operator FixedPoint(float oc)     
{         

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

... usage

FixedPoint myNumber = (FixedPoint)0.5f;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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