简体   繁体   English

C#隐式运算符和ToString()

[英]C# Implicit operators and ToString()

I'm creating my own type for representing css values (like pixels eg. 12px ). 我正在创建自己的类型来表示css值(例如像素,例如12px)。 To be able to add/subtract/multiply/... my type and ints I've defined two implicit operators to and from int. 为了能够添加/减去/乘以/ ...我的类型和整数我已经在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. 我得到“10”而不是“10px” - 使用隐式转换为int而不是ToString()方法。 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. 是的,有一个隐式转换为intWriteLine(int)的重载比WriteLine(object)更具体,所以它会使用它。

You could explicitly call the WriteLine(object) overload: 您可以显式调用WriteLine(object)重载:

Console.WriteLine((object)c1);

... or you could call ToString yourself, so that Console.WriteLine(string) is called: ...或者您可以自己调用ToString ,以便调用Console.WriteLine(string)

Console.WriteLine(c1.ToString());

... or you could just remove the implicit conversion to int . ...或者你可以删除隐式转换为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.) 我一般不主张对这样的事情隐式转换的...(你可以保持隐式转换,从 int当然,如果你真的想。)

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

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

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

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