c#中克隆对象属性_C ++中的对象属性

c#中克隆对象属性

Many modern programming languages support the concept of a

许多现代编程语言都支持a

property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automatically each time the field/variable is used.  Alas, standard C++ does not directly support such a concept, but this article discusses some options you can use to implement properties in your C++ objects.

Properties are a first-class language element of C#, Visual Basic, Delphi, Python and other languages.  Over the years, proposals have been submitted to C++ standards committee to add the feature to our favorite programming language, but it's never quite made it into an official standard.

属性是C#,Visual Basic,Delphi,Python和其他语言的一流语言元素。 多年来,已经向C ++标准委员会提交了提案,以将该功能添加到我们最喜欢的编程语言中,但从未完全将其成为正式标准。

为什么选择属性?
(Why Properties?
)

重点是什么? 为什么要使用属性?

The main idea is based on something that programmers have been struggling with probably ever since Lady Lovelace wrote the first computer algorithm -- data encapsulation.  You want to manage and limit direct access to data elements so that only those parts of the program that need it can get to it.  But the usefulness of properties goes well beyond that.  Here are some things you can do with properties and some examples:

主要思想是基于Lady Lovelace编写第一个计算机算法(数据封装)以来程序员一直在努力的事情。 您想要管理和限制对数据元素的直接访问,以便只有程序中需要它的那些部分才能访问它。 但是属性的用途远不止于此。 这是您可以使用属性执行的一些操作以及一些示例:

Data encapsulation, data hiding.  Prevent direct manipulation of data elements.  Avoid programming errors related to changing a data value incorrectly or at the wrong time. 数据封装,数据隐藏。 防止直接操纵数据元素。 避免与错误地或在错误的时间更改数据值相关的编程错误。



Example: Protecting list integrity in a multi-threaded program; e.g., transparently apply a lock or a critical section around code that manipulates the list.

Data validation; data value enforcement.  It's a way for you to make your object self-correcting.

Examples: Forcibly "pin" a data value so that it is guaranteed to be within a certain range of valid values.  For instance, ensuring that a "percentage" variable will be between 0 and 100, inclusive.  Make sure that a ZIP Code is exactly five or nine digits.

数据验证; 数据价值执行。 这是使您的对象自我校正的一种方法。


Transparent data manipulation.  The data itself might be stored in a form that is inconvenient for other parts of the program to use.  The property logic does a conversion transparently. 透明的数据处理。 数据本身可能以不方便程序其他部分使用的形式存储。 属性逻辑透明地进行转换。



Examples:  Encrypt a password, Social Security Number, or other sensitive data when stored but have the clear-text value at hand when used in the program.  Provide normalized handling for database NULL values.  Transparently "escape" and "unescape" text that is to be displayed in an HTML page or used in an SQL query.

Data source transparency.  The programmer (and the rest of the system) does not need to know exactly how or from where the data was obtained.  He just needs the value. 数据源透明度。 程序员(以及系统的其余部分)不需要确切地知道如何或从何处获取数据。 他只需要价值。



Example:  The value is obtained through a COM-object method that might, in turn, access a database hosted on a remote system.  But it looks like a local memory variable in the program code.

Invoke a function call to get or set the data by using simple assignment semantics.  Hide the "dirty" low-level implementation.  This is possibly the most commonly-cited value of properties.

Examples:  Instead of calling MoveWindow(...), you can just set oWin.rPos=r;  Instead of calling ShowWindow(h,SW_HIDE) just set oWin.fIsVisible=false; Rather than calling SetPixel(x,y,rgbColor) just use Canvas[y][x]=rgbColor;  Instead of calling GetPrivateProfileString() for a user-settings option value, just use sUser=oSettings.sUserName;

通过使用简单的赋值语义来调用函数调用以获取或设置数据。 隐藏“脏”的低级实现。 这可能是最常引用的属性值。

oWin.rPos = r;而不是调用MoveWindow(...) 不用设置ShowWindow(h,SW_HIDE)而是设置 oWin.fIsVisible = false;即可。 不用调用SetPixel(x,y,rgbColor)而是使用 Canvas [y] [x] = rgbColor; 不用为用户设置选项值调用GetPrivateProfileString(),只需使用 sUser = oSettings.sUserName;即可。

存取器:
(Accessors: getters and putters
)

If you recognized any of the above scenarios (that is, if you have done much C++ coding), you have probably written your share of getXxxx() and putXxxx() member functions in your class objects.  And you have run into the problem:  Using accessor methods can be syntactically awkward:

如果您认识到以上任何一种情况(也就是说,如果您已完成许多C ++编码),则可能已编写了get 共享并将成员函数放在类对象中。 而且您遇到了一个问题:使用访问器方法在语法上可能很尴尬:

oList.putElement( n, oList.getElement(n)+1 ); // thread-safe getter+putter
oAddr.putZIP( sZip );   // range-enforcement putter
oWin.putPosition( r );  // hidden-details putter
oList[n]++;            // could use thread-locking logic 
oAddr.sZipCode= sZip;  // could enforce valid content (5 or 9 digits)
oWin.Position= r       // calls MoveWindow()

In short, that's what this is all about:  Anything that you can do with a property can be done with a pair of get/put member functions, but the programming is not as convenient.  Why should VB and C# programmers have all of that heavenly convenience while we poor C++ programmers are damned to spend eternity in a get-and-put purgatory?

简而言之,这就是全部内容: 对属性所做的任何事情都可以通过一对get / put成员函数来完成,但是编程并不那么方便。 为什么我们贫穷的C ++程序员被诅咒在永恒的炼狱中度过永恒的时光,为什么VB和C#程序员应该拥有如此巨大的便利呢?

Well, we are not.  First, several popular C++ compilers provide non-standard support for properties.  But even lacking direct support, the C++ language boasts the ability to write operator overrides... and that means that it is possible to implement property semantics.

好吧,我们不是。 首先,几种流行的C ++编译器为属性提供非标准支持。 但是,即使缺乏直接支持,C ++语言也具有编写运算符覆盖的能力……

C ++属性实现
(C++ Property Implementations
)

一些编译器提供了非标准扩展,并且有多种使用模板和/或宏来解决问题的方法。 让我们看一下选项。

Non-Standard Extensions

非标准扩展

For many of us, the first and most obvious place to look is in our compiler's documentation.  If it provides a non-standard extension with support for properties, then unless you intend to port the code to a different compiler, why not use it?

对于我们中的许多人来说,第一个也是最显而易见的地方是我们的编译器文档。 如果它提供了对属性的支持的非标准扩展,那么除非打算将代码移植到其他编译器,否则为什么不使用它呢?

Microsoft's Visual C++Microsoft的Visual C ++

      __declspec( property( get=YourGetFn, put=YourPutFn ) ) int yourPropVarName;

__declspec(property(get =

... in your class declaration.  Code up the YourGetFn and YourPutFn and add the private variable that they will access, and you are done.

...在您的类声明中。 对

// Range-check and "correct" a percentage value
//
class PollData {
private:
    int mp_nPrivateValue;
public:
    void putPct(int n) {              // enforces a specific range of values
        mp_nPrivateValue= n;
        if (n>100) mp_nPrivateValue= 100;
        if (n<0)   mp_nPrivateValue= 0;
    }
    int getPct() {
        return mp_nPrivateValue;
    }
    __declspec(property(get= getPct, put= putPct)) int nPct; // <<-- property name
};
void main() {
    PollData rPD;
    rPD.nPct= 200;  // pinned to 100
    rPD.nPct= -10;  // pinned to 0
    rPD.nPct++;     // internally calls getPct and putPct
   // r.mp_nPrivateValue=50; // Compile error: "cannot access private member"
}

property to first class status and you don't need to use the somewhat awkward _declspec syntax in the declaration when doing .NET progamming).

属性设置为一流状态,并且在进行.NET编程时,无需在声明中使用有些尴尬的_declspec语法 )。

Note that the semantics are perfect -- property variables work transparently to the code that uses them.  For instance, you can use syntax like propVar++ and it will correctly do a get, add 1, and then do the put.

请注意,语义是完美的-属性变量对使用它们的代码透明地起作用。 例如,您可以使用propVar ++之类的语法,它将正确执行get,加1和put的操作。

Borland's (now Embarcadero's) C++ Builder supports this using the __property keyword.  There is an example of use here (midway down the page).

Borland(现在为Embarcadero)的C ++ Builder使用__property关键字支持此功能。 有使用的例子在这里 (中途下页)。

For Apple programmers, Objective C++ provides non-standard support using the @property directive.  See an example here.

对于Apple程序员, Objective C ++使用@property指令提供非标准支持。 在这里查看示例。

Support using only Standard C++

仅支持使用标准C ++

In researching this article, I found a number of "solutions" to the C++ property "problem."  I also found many vociferous opinions.  A lot of people think that C++ has no need to be more "VB-like," while others embrace the idea wholeheartedly.  Anyway, here are of few of the Standard C++ implementations that I found.

在研究本文时,我发现了C ++属性“问题”的许多“解决方案”。 我也发现了很多意见。 许多人认为C ++不必更加“类似于VB”,而其他人则全心全意地接受该想法。 无论如何,这里是我发现的一些Standard C ++实现。

This CodeGuru article uses a template and operator overloads to accomplish the goal.  It also includes the ability to make a property that is read-only or write-only:

此CodeGuru文章使用模板和运算符重载来实现目标。 它还包括使属性成为只读或仅写的能力:



    Implementing a Property in C++

在C ++中实现属性


   
http://www.codeguru.com/Cpp/Cpp/cpp_mfc/article.php/c4031 http://www.codeguru.com/Cpp/Cpp/cpp_mfc/article.php/c4031

This CodeProject article uses a template and creates an object for each property variable.  That's an innovative idea, but the added overhead makes it rather inefficient.

此CodeProject文章使用模板并为每个属性变量创建一个对象。 这是一个创新的想法,但是增加的开销使其效率很低。



    Implementing Properties In C++

在C ++中实现属性


   
http://www.codeproject.com/KB/cpp/cppproperties.aspx http://www.codeproject.com/KB/cpp/cppproperties.aspx

This CodeProject article uses a complex set of macros to do the trick, but also includes support for using the Microsoft extension if desired.  You might also want to read some of the user comments, which describe and illustrate some alternative techniques.

这篇CodeProject文章使用一组复杂的宏来完成操作,但如果需要,还包括使用Microsoft扩展的支持。 您可能还需要阅读一些用户评论,这些评论描述和说明了一些替代技术。



    Generic C++ Properties

通用C ++属性


   
http://www.codeproject.com/KB/cpp/genericproperty.aspx http://www.codeproject.com/KB/cpp/genericproperty.aspx

The following article is a full-featured implementation, with a great description of the internal workings of its ultra-complex system of typedefs, templates, and operator overloads.

下一篇文章是功能全面的实现,它很好地描述了其超复杂的typedef,模板和运算符重载系统的内部工作原理。



    C++ implementation of the C# Property and Indexer with Accessor-Modifiers

具有访问者修饰符的C#属性和索引器的C ++实现


   
http://www.codeproject.com/KB/cpp/cpp_property_indexer.aspx http://www.codeproject.com/KB/cpp/cpp_property_indexer.aspx

A user comment added to this article includes a simpler, but less versatile template-based system:

添加到本文的用户评论包括一个更简单但用途较少的基于模板的系统:



    Defining Properties in C++ similar to C#

在C ++中定义类似于C#的属性


   
http://www.cplusplus.com/forum/general/8147/ http://www.cplusplus.com/forum/general/8147/

EE's own

EE自己的

evilrix has published an article for Standards-bound C++ coders.  It uses a set of macros, including token-pasting to create the get/put functions and the friend functions for operator overrides.  As with most similar implementations I've seen, it lacks semantic support for evilrix发表了一篇针对标准绑定C ++编码器的文章。 它使用一组宏,包括令牌粘贴来创建get / put函数以及用于操作符覆盖的Friend函数。 与我所见过的大多数类似实现一样,它缺乏对 ++ and +++= and other often-used operators. + =以及其他常用运算符的语义支持。

    How to add properties to standard C++ classes

如何向标准C ++类添加属性


   
https://www.experts-exchange.com/A_3843-How-to-add-properties-to-standard-C-classes.html https://www.experts-exchange.com/A_3843-How-to-add-properties-to-standard-C-classes.html

This whitepaper by Lois Goldwaite proposes that property support be made available as a part of the standard C++ library. The first part of the article is an excellent introduction to the issues.  And, the article includes a template-based implementation.

Lois Goldwaite撰写的此白皮书建议将属性支持作为标准C ++库的一部分提供。 本文的第一部分是对这些问题的出色介绍。 并且,本文包括基于模板的实现。



    C++ Properties -- a Library Solution

C ++属性-库解决方案


   
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1615.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1615.pdf

结论
(Conclusion
)

我大体上同意路易斯·戈德韦特(Lois Goldwaite)的观点,认为整个属性都等于“句法糖精”,即在基础牛轧糖上的糖衣。 我通常宁愿只添加get Xxxx and a put Xxxx functions (and do all of the "hard work" of using them when I access certain fields) than apply a complex set of templates and macros.

However, I disagree that it should never be part of the C++ standard.  If property were elevated into a first class language keyword, I'd probably use it all of the time.   My advice is that if you don't mind stepping outside of the official C++ standard, and if your compiler supports the feature (even as a non-standard extension)... use it!

但是,我不同意它永远不应该成为C ++标准的一部分。 如果将属性提升为一流的语言关键字,我可能会一直使用它。 我的建议是,如果您不介意超出官方C ++标准的范围,并且如果您的编译器支持该功能(甚至作为非标准扩展名),请

The usefulness of "smart fields" cannot be questioned.  Data validation, source transparency, true encapsulation, and the value of hiding (and being able to change) implementation details such as OS/GUI-related API calls --- all covered with a "syntactic sucralose" to make it easy to use... sounds sweeeeet to me!

毫无疑问,“智能字段”的有用性。 数据验证,源透明性,真正的封装以及隐藏(并能够更改)实现细节(例如与OS / GUI相关的API调用)的价值-所有这些都覆盖了“语法三氯蔗糖”,以使其易于使用。 ..听起来对我来说

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=

If you liked this article and want to see more from this author, please click the Yes button near the:

如果您喜欢这篇文章,并希望从该作者那里获得更多信息 ,请单击旁边的按钮:

      Was this article helpful?

本文是否有帮助?

label that is just below and to the right of this text.   Thanks!

此文字下方和右侧的标签。

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

=-=-=-=-=-=-=-=-=-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=-=- =-=-=-=

翻译自: https://www.experts-exchange.com/articles/3912/Object-Properties-in-C.html

c#中克隆对象属性

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值