hoperce
V2EX  ›  问与答

C#其他类型转字符串!

  •  
  •   hoperce · Jun 1, 2012 · 4639 views
    This topic created in 5291 days ago, the information mentioned may be changed or developed.
    加空字符串("") 和 ToString() 和 (string) 有什么区别和代价么?
    6 replies  •  1970-01-01 08:00:00 +08:00
    avatasia
    avatasia
    Jun 1, 2012❤️1
    1
    你是要说string s = 10 + ""; 这样子算加空字符串?还是什么?
    3.5还是4.0之后,int直接支持和string相加, 默认转型了,效率上有点问题。
    ToString()用的比较多, (string)很少用到,不推荐使用。
    里面涉及到装箱拆箱的基础知识,string.format()这个效率最高,具体你可以看看陆敏技的书或者CLR via C#
    acterce
    acterce
    Jun 1, 2012
    2
    呔! 秃驴
    caoyue
    caoyue
    Jun 1, 2012❤️1
    3
    加空字符串不推荐。虽然同样是由 CLR 自动调用了 Tostring() ,但字符串的操作会生成两个副本等待 GC 回收。
    一般是用 Tostring() 或是 Convert.Tostring() ,区别是 Object 为 Null 的时候前者会异常而后者会返回空字符串。
    强制转换要求对象运行时类型是 string ,否则就会异常,不推荐使用。
    hoperce
    hoperce
    OP
    Jun 1, 2012
    4
    @acterce 额。
    hoperce
    hoperce
    OP
    Jun 1, 2012
    5
    @caoyue 但是ToString()在对象为空的时候会出现异常!Convert.ToString()表示没用过!
    hoperce
    hoperce
    OP
    Jun 1, 2012
    6
    @avatasia 3.5和4.0都有。 string s=object+""这样的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2011 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:19 · PVG 23:19 · LAX 07:19 · JFK 10:19
    ♥ Do have faith in what you're doing.