简体   繁体   中英

c# implicit operator

I'm writting an application that runs user defined algorithms. I want to keep track of variables used, so I created class TVar that will raise events when they are altered or peeked. I already did

public static implicit operator int(TVar v)
{
    Tracker.Track(v.name, EventType.Variable, EventAction.Peek, v.var);
    return (int)v.var;
}

Now I want to know when user changes value, and i Had

public static implicit operator TVar(int i)
{
    Tracker.Track(/* I need TVar.Name here */, EventType.Variable, EventAction.Change, i);
    return new TVar(i);
}

But as you may have noticed I use "name" to identify different TVars. Now, I create new TVar var1 and name it "first var", do some stuff with it (Tracker recieves information) and when i change var1 to some other int it looses it's name(because i returned new TVar, not the actual one) Help please!

That won't work the way you want it to, because when you define an implicit conversion operator you cannot access the l-value from within the operator body. An assignment, by definition, always discards the value that the variable was referencing (if any).

TVar foo = new TVar("Foo", 13);
foo = 42;

After the first line foo is initialized, and it references an instance of TVar . But the second line discards foo's old value and replaces it with another TVar instance.

The only way to achieve what you want is to make an instance (non-static) method TVar.Assign(int) .

public void Assign(int value)
{
    this.Value = value;
    Tracker.Track(this.Name, ...);
}

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