C # “Boxing” in ownership / 1-Arg Designated by purpose

In C #, suppose you have a simple class:

public class MyFloat
{
    public float Value { get; set; }

    public MyFloat()
    {}

    public MyFloat(float _Value)
    {
        Value = _Value;
    }
}

Is there such a syntax that allows you to briefly initialize the Value property, something like:

MyFloat[] Arg_f;
Arg_f = new MyFloat[] { 1, 2, 3 };

Instead of explicitly calling the constructor, for example:

Arg_f = new MyFloat[] { new MyFloat(1), new MyFloat(2), new MyFloat(3) };

Or, what is the same, i.e.

MyFloat myFloat = 5f;          //Implicitly assign 5f to myFloat.Value
float myFloatValue = myFloat;  //Implicitly get myFloat.Value

This obviously looks like boxing / unboxing, except that I am trying to “insert” into a specific property of an object. Or you can say that I'm trying to implicitly call the 1-arg constructor as intended.

Is something like this possible in C #, or am I just on a wild goose chase?

+4
source share
1 answer

This is possible using an implicit conversion :

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

Now this will work:

 var myFloats = new MyFloat[] { 1, 2 };

, , /unboxing, , "" .

, , , .

, , . ( " MyFloat?" ) .

+8

Source: https://habr.com/ru/post/1612497/


All Articles