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开发者_如何学Python 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.)
Override the "ToString()" method and use c1.ToString().
Just override the ToString method in CssUnitBase and call that when you want it as a string.
加载中,请稍侯......
精彩评论