如果我的以下任何理解不准确,请告诉我。
MyClass m = new MyClass()
<---> MyClass * m = new MyClass;
- >??? (没有等效的 C#)<--->
MyClass m(5,"foo");
void SomeMethod(ref Widget w)
<---> void SomeMethod(Widget & w)
或 void SomeMethod(Widget * * w)
void SomeMethod(Widget w)
<---> void SomeMethod(Widget * w)
???
(没有等效的 C#)<---> void SomeMethod(const Widget)
???
(没有等效的 C#)<---> void SomeMethod(const & Widget)
void SomeMethod(out Widget w)
<---> ??? (没有 C++ 等价物)
C# 和 C++ 非常不同,比它们的名字所暗示的要多得多,但无论如何我都会尝试:
MyClass m = new MyClass() <---> MyClass * m = new MyClass;
大致等同,只是 C# 会在不再使用后收集 m
。使用 C++,您必须记住 delete
对象。在 C++ 中,分配到堆栈或使用智能指针更为惯用。
??? (no C# equivalent) <---> MyClass m(5,"foo");
C# 无法让您对对象的分配位置进行太多控制。但是,它具有可以避免堆分配的 struct
类型。
void SomeMethod(ref Widget w) <---> void SomeMethod(Widget & w) or void SomeMethod(Widget * * w)
这些是相似的,但在 C# 中 ref
通常应该避免。
void SomeMethod(Widget w) <---> void SomeMethod(Widget * w)
这里的主要区别在于,在 C++ 中,任何拥有对象指针的人都可以删除它。在 C# 中,垃圾收集器处理删除。 C# 有点像使用 std::shared_ptr
,但带有循环检测。
??? (no C# equivalent) <---> void SomeMethod(const Widget)
??? (no C# equivalent) <---> void SomeMethod(const & Widget)
C# 没有像 C++ 那样强大的 const
概念。通常,必须在每个字段上使用 readonly
关键字使整个类型不可变。
void SomeMethod(out Widget w) <---> ??? (no C++ equivalent)
在 C++ 中,通过引用获取对象可以实现与 out
变量相同的效果。 out
变量通常是不好的做法,所以这个关键字是一种文档形式。
最重要的是,花时间了解如何用每种语言编写代码。许多概念是共享的,但要真正利用一项技术,您应该使用它,而不是试图将一种范式强加到另一种范式中。