C#字符串格式,基数或无基数 [英] C# string format, base or no base

查看:144
本文介绍了C#字符串格式,基数或无基数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public class Eagle : Bird
    {
        public Eagle():base()
        { }

        public Eagle(string name, string id, double age, CategoryType category, GenderType gender, BirdSpecies birdSpecie)
            : base(name, id, age, category, gender)
        {
            birdSpecie = BirdSpecies.Eagle;
        }

        public override string ToString()
        {
            //return string.Format("{0}", base.ToString());
            //return string.Format("{0} {1} {2} {3} {4}", Name, ID, Age, Category,                   Gender);
        }





为什么第二个格式化的字符串工作



Why is it that the second formatted string works

return string.Format("{0} {1} {2} {3} {4}", Name, ID, Age, Category,                   Gender);







whereas

return string.Format("{0}", base.ToString());





未能这样做。是否由于与构造函数混淆了?是导致错误的默认空构造函数吗?



fails to do so. Is it due to some mix-up with the constructors? Is the default empty constructor that is causing the error?

推荐答案

不,没有混淆。这个问题很简单。这两个代码行几乎没有任何共同点,因此答案取决于您想要实现的目标。谁告诉你 base.ToString()应该做任何有用的事情,特别是你没有在你的基类中重写这个方法。



为了帮助你理解发生了什么,我会告诉你:如果你返回 string.Format({0},base.ToString() ); 来自你的 ToString 实现在功能上完全等同于不重写此方法。您只需尝试返回基类返回的完全相同的值。这不是很明显吗?



-SA
No, there is no "mix-up". The problem is trivial. These two code lines have almost nothing in common, so the "answer" would depend on what you want to achieve. Who told you base.ToString() is supposed to do anything useful, especially in you did not override this method in your base class.

To help your to understand what''s going on, I''ll tell you: if you return string.Format("{0}", base.ToString()); from your ToString implementation functionally is strictly equivalent to not overriding this method at all. You simply try to return exact same value the base class returns. Isn''t that obvious?

—SA


这篇关于C#字符串格式,基数或无基数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆