Code :
public class t : System.Dynamic.DynamicObject
{
public dynamic Value;
public static implicit operator t(int value)
{
if (value > 100) value = 100;
t x = new t();
x.Value = value;
return x;
}
}
Usage :
dynamic f = new t();
f = 44; // the implicit operator doesn't get called
However if I change implicit
to explicit
and use it like f = (int)44)
the explicit operator is called.
EDIT: I want my class to inherit from DynamicObject.
How to fix this issue ?
You use:
dynamic f = new t(); // f has type 'dynamic', no compile-time link between f and type 't'
f = 44; // the implicit operator doesn't get called
Why would assigning 44
to a variable of type dynamic
convert that 44
through any user-defined operator? It simply puts 44
(or rather a boxed 44
) into f
.
Compare with:
t f = new t();
f = 44;
When you set f = 44;
, it is not changing the value of the object. Rather, it is reassigning the f
variable to point to a new object . By default, the new object will be an int
, since it's an int
literal. If you want to create a new t
object that equals 44
, you need to cast it to that type, like this:
f = (t)44;
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.