c# - C++和C#中指针和函数参数的等价性

标签 c# c++ .net

<分区>

如果我的以下任何理解不准确,请告诉我。

  1. MyClass m = new MyClass() <---> MyClass * m = new MyClass;
  2. >??? (没有等效的 C#)<---> MyClass m(5,"foo");
  3. void SomeMethod(ref Widget w) <---> void SomeMethod(Widget & w)void SomeMethod(Widget * * w)
  4. void SomeMethod(Widget w) <---> void SomeMethod(Widget * w)
  5. ???(没有等效的 C#)<---> void SomeMethod(const Widget)
  6. ???(没有等效的 C#)<---> void SomeMethod(const & Widget)
  7. 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 变量通常是不好的做法,所以这个关键字是一种文档形式。

最重要的是,花时间了解如何用每种语言编写代码。许多概念是共享的,但要真正利用一项技术,您应该使用它,而不是试图将一种范式强加到另一种范式中。

关于c# - C++和C#中指针和函数参数的等价性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055095/

相关文章:

c# - 使用 propertyGrid 时出现 System.MissMethodException

java - 将 nonfree 包含到 opencv4android

c# - 如何限制 .NET DynamoDB 中 context.Query 的结果数量

c# - 使用 O(1) 内存、O(n) 运行时复杂度且无双重枚举实现 LINQ "chunk by predicate"

c# - 防止字符串中出现西里尔文/希腊文/中文 - C# 4.0

c# - 将子类的枚举器强制转换为父类的枚举器是否错误?

c# - WPF 标签到文本框

C# RestSharp PUT 方法并发送原始字节 (protobuf)

c++ - gcc 6.1 std::result_of 编译错误

c# - 如何最好地将字节数组从 C# 获取到 C++ WinRT 组件