简体   繁体   中英

Reference to left hand side on implicit cast operator

Is there a way I can get an instance of the left hand side of the operation when overloading an implicit cast from int to A ?

Like this:

public class A
{
    int myInt;
    public static implicit operator A(int x)
    {
        a.myInt = x;
    }
}

and then

A myA = new A();
myA = 2;

so that myA.myInt is 2

I searched on the internet but I couldn't find an answer to this exact problem. I don't think it is possible since it is a static function and it will throw you an error if you try to put two parameters into the function. Also, I can see this would give you an error if you tried to do this on a null variable (like if I had declared it like this A myA; ). But then you could do it in a struct (because as far as I know structs can't ever be null - or can't be assigned null -, please correct me if I'm wrong).

I'm just wondering if there is some sort of wizardry that I could do to make something like this work.

You cannot get a reference to myA.myInt or any other left side, because it is not always there.

Here is an example when determining the left side would be problematic:

void Foo(A a) {...}
...
Foo(2);

Above, calling Foo(2) requires invoking your implicit conversion operator, yet its return value is not assigned to anything other than Foo 's a parameter, which is not a variable that would be available in the caller.

Demo.

This is not possible. The implicit operator returns a value. It is the code generated by the C# compiler that calls that code to get the value and use it in whatever way the caller indicates it should be used.

It's worth noting that there may not even be a storage location. If someone writes SomeMethodThatAcceptsAnAInstance(2) then you're not storing the results of the implicit conversion in a variable. You could also write A a = 2; in which a is an uninitialized variable until the implicit operator's value is set to it, so the storage location does not have valid state at the time the implicit operator is called.

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