如何在C#中重载Console.WriteLine()方法? 在C++中,我可以做如下: Class foo(){ int x; friend ostream& operator<<(ostream& os, const Date& dt); ... }; ostream& operator<<(ostream& os, const foo& f) { os << f.x; return os; } int main(){ Foo foo1, foo2, foo3; std::cout << foo1 << foo2 << foo3; return 0; }

如何在C#中重载Console.WriteLine()方法? 在C++中,我可以做如下: Class foo(){ int x; friend ostream& operator<<(ostream& os, const Date& dt); ... }; ostream& operator<<(ostream& os, const foo& f) { os << f.x; return os; } int main(){ Foo foo1, foo2, foo3; std::cout << foo1 << foo2 << foo3; return 0; },c#,C#,Console.WriteLine调用其参数的虚拟ToString方法,因此只需覆盖它: public class Foo { private Int32 x; public override String ToString() { return this.x.ToString(); } } 重写Foo的ToString实现。您应该首先初始化Foo,然后重写ToString()发生在我们当中最好的情况。:) public class Foo {

Console.WriteLine
调用其参数的虚拟
ToString
方法,因此只需覆盖它:

public class Foo {
    private Int32 x;
    public override String ToString() {
        return this.x.ToString();
    }
}

重写
Foo
ToString
实现。您应该首先初始化
Foo
,然后重写
ToString()
发生在我们当中最好的情况。:)
public class Foo {
    private Int32 x;
    public override String ToString() {
        return this.x.ToString();
    }
}