简体   繁体   English

c#隐式运算符

[英]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. 我想跟踪所使用的变量,因此我创建了类TVar,它将在更改或查看时引发事件。 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! 现在,我创建新的TVar var1并将其命名为“first var”,用它做一些事情(Tracker接收信息),当我将var1更改为其他int时,它会丢失它的名称(因为我返回了新的TVar,而不是实际的)请帮助!

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. 这不会按照您希望的方式工作,因为当您定义隐式转换运算符时,您无法从运算符主体中访问l值。 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 . 在第一行foo初始化之后,它引用了TVar一个实例。 But the second line discards foo's old value and replaces it with another TVar instance. 但是第二行丢弃了foo的旧值并将其替换为另一个TVar实例。

The only way to achieve what you want is to make an instance (non-static) method TVar.Assign(int) . 实现你想要的唯一方法是创建一个实例(非静态)方法TVar.Assign(int)

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

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

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