简体   繁体   中英

C# Implicit operators and ToString()

I'm creating my own type for representing css values (like pixels eg. 12px ). To be able to add/subtract/multiply/... my type and ints I've defined two implicit operators to and from int. Everything works great except one thing.. If I write:

CssUnitBase c1 = 10;
Console.WriteLine(c1);

I get "10" instead of "10px" - implicit conversion to int is used instead ToString() method. How can I prevent that?

Yes, there's an implicit conversion to int and the overload of WriteLine(int) is more specific than WriteLine(object) , so it'll use that.

You could explicitly call the WriteLine(object) overload:

Console.WriteLine((object)c1);

... or you could call ToString yourself, so that Console.WriteLine(string) is called:

Console.WriteLine(c1.ToString());

... or you could just remove the implicit conversion to int . Just how useful is it to you? I'm generally not in favour of implicit conversions for this sort of thing... (You could keep the implicit conversion from int of course, if you really wanted to.)

重写“ToString()”方法并使用c1.ToString()。

只需覆盖CssUnitBaseToString方法,并在需要时将其作为字符串调用。

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