[英]How to define properties with a handwritten getter/setter in managed C++?
I need to define properties with handwritten getters/setters in a managed C++ project, in a class that will be usable from a C# .NET project. 我需要在托管C ++项目中使用可从C#.NET项目使用的类中的手写getter / setter定义属性。
The codeproject article on the subject recommends the __property float Volume;
有关该主题的代码项目文章建议使用__property float Volume;
which is outdated and now classified as /crl:oldSyntax
. 已过时,现在分类为/crl:oldSyntax
。
The Open Standard managed extensions to C++ article says that defining properties like property float Volume;
C ++的开放标准托管扩展文章说,定义诸如property float Volume;
automatically generate a backing field, which I don't want or need. 自动生成我不需要或不需要的支持字段。
Simply defining properties like property float Volume;
只需定义诸如property float Volume;
compiles fine with /clr
, but attempting to add handwritten getters/setters like float Mixer::Volume::get(){ .. }
throw Error C2084: function X already has a body
. 可以使用/clr
正常编译,但是尝试添加手写的getter / setter,例如float Mixer::Volume::get(){ .. }
throw Error C2084: function X already has a body
。
So what is the proper way to define read-only or read/write properties without a backing field, and with custom-built handwritten getter/setter methods? 那么,没有后备字段并使用定制的手写getter / setter方法来定义只读或读/写属性的正确方法是什么?
You have found the header-only version by yourself. 您已经找到了仅标头版本。 If you want to implement the getters and setters in a cpp file, the syntax is as follows: 如果要在cpp文件中实现getter和setter,则语法如下:
///////////////////////
// Foo.h:
///////////////////////
ref struct Foo
{
property float Volume
{
float get();
private: void set(float value);
}
private:
float m_backingField;
}
///////////////////////
// Foo.cpp:
///////////////////////
float Foo::Volume::get()
{
return m_backingField;
}
void Foo::Volume::set(float value)
{
m_backingField = value;
}
Edit: Some additional information : 编辑:一些其他信息 :
__property
keyword came from the managed extensions and is now deprecated. 双下划线__property
关键字来自托管扩展,现已弃用。 Well I found you have to declare the property only ONCE in the header file, as follows: 好吧,我发现您必须在头文件中仅声明该属性,如下所示:
property float Volume {
float get() {
return 0;
}
void set(float value) {
}
}
If you declare the property like the follows, a backing field is automatically generated: 如果按如下所示声明属性,则会自动生成一个后备字段:
property float Volume;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.