C# 隐式运算符和 ToString()
我正在创建自己的类型来表示 css 值(例如像素,例如 12px )。为了能够对我的类型和整数进行加/减/乘/...我已经在 int 之间定义了两个隐式运算符。除了一件事之外,一切都很好。如果我写:
CssUnitBase c1 = 10;
Console.WriteLine(c1);
我得到“10”而不是“10px” - 使用隐式转换为 int 而不是 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,存在到
int
的隐式转换,并且WriteLine(int)
的重载比WriteLine(object)
更具体,因此它会用那个。您可以显式调用
WriteLine(object)
重载:...或者您可以自己调用
ToString
,以便Console.WriteLine (string)
被调用:...或者您可以删除到
int
的隐式转换。它对你有多大用处?我通常不赞成对此类事情进行隐式转换...(当然,如果您真的愿意,您可以保留 fromint
的隐式转换。 )Yes, there's an implicit conversion to
int
and the overload ofWriteLine(int)
is more specific thanWriteLine(object)
, so it'll use that.You could explicitly call the
WriteLine(object)
overload:... or you could call
ToString
yourself, so thatConsole.WriteLine(string)
is called:... 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 fromint
of course, if you really wanted to.)重写“ToString()”方法并使用 c1.ToString()。
Override the "ToString()" method and use c1.ToString().
只需重写 CssUnitBase 中的 ToString 方法,并在需要将其作为字符串时调用该方法即可。
Just override the
ToString
method inCssUnitBase
and call that when you want it as a string.