C++/CLI 中的属性是什么?

lit*_*tuk 7 c++-cli properties

我在 C++ 代码中看到了这个术语property。我认为它与 C++/CLI 有关。

究竟是什么?

Cod*_*ray 6

它确实与 C++/CLI 有关(非托管 C++ 并没有真正的属性概念)。

属性是行为类似于字段的实体,但由 getter 和 setter 访问器函数在内部处理。它们可以是标量属性(它们的行为类似于字段)或索引属性(它们的行为类似于数组)。在旧语法中,我们必须直接在代码中指定 getter 和 setter 方法来实现属性 - 正如您可能猜到的那样,这并没有那么受欢迎。在 C++/CLI 中,语法更接近 C#,并且更易于编写和理解。

摘自本文:http://www.codeproject.com/KB/mcpp/CppCliProperties.aspx

另请参阅有关 C++/CLI 属性的MSDN 。

示例代码:

private:
   String^ lastname;

public:
   property String^ LastName
   {
      String^ get()
      {
         // return the value of the private field
         return lastname;
      }
      void set(String^ value)
      {
         // store the value in the private field
         lastname = value;
      }
   }
Run Code Online (Sandbox Code Playgroud)

  • 不,它们(C++/CLI 属性)的行为不像字段(或成员变量,如果您愿意的话)。这就是重点。它们使用相同的语法进行访问(除了禁止获取地址),但具有不同的行为。此外,完全可以在非托管 C++ 中编写属性,只是没有“property”关键字来帮助您。 (2认同)