复制类属性 [英] Copy Class Properties

查看:96
本文介绍了复制类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





如何使用byval方法将类的所有属性复制到另一个类?

Hi,

How to copy all properties of a class to another class using byval method?

Dim Xglobal as new NameClass
Dim Xlocal as new NameClass


XLocal = XGlobal





i使用上面的方法,它运作良好,但是当我更改xglobal类中的属性值,它也会自动更改xlocal属性的值。 (我想分配像byval methoid这样的值。)



i use the above method, it works good, but when i change a property value in xglobal class it automatically changes the values of xlocal properties also. (I want to assign the values like byval methoid).

推荐答案

Quote:

XLocal = XGlobal

XLocal = XGlobal

上面的行只是将引用 XGlobal 分配给 XLocal :它们是两个变量持有对同一个对象的引用



您应该使用 MemberwiseClone [ ^ ]方法。但请,请,请确保理解浅层副本(以及深层副本),即:r 仔细阅读文档(以及代码示例)。

The above line simply assigns the reference XGlobal to XLocal: they are then two variables holding the reference to the same object.

You should instead use MemberwiseClone[^] method. However, please, please, please, make sure to understand what a shallow copy is (and what a deep copy is), that is: read carefully the documentation (and the code example).


您需要提供 Copy()方法;),它返回具有默认属性的新类。



You need to provide Copy() method ;) which returns new class with default properties.

in pseudo-code:
Class NameClass

    'declare and implement many properties and methods

    'provide Copy method
    Public Function Copy() As NameClass
        Dim newClass As NameClass
        newClass.Property1 = Me.Property1
        newClass.Property2 = Me.Property2
        Return New newClass
    End Function

    'another members of class

End Class





用法:



Usage:

Dim Xglobal as new NameClass
With Xglobal
   'here set properties
End With

Dim Xlocal as new NameClass = Xglobal.Copy() 'simple?


成员克隆

在NameClass中创建一个新的公共函数克隆

Member-wise clone
create a new public function clone in your NameClass
Public class NameClass
   Public Function clone() As NameClass
        Dim ObjOriginal = Me
        Dim ObjCopied As New NameClass
        'set desired property values from original object to the object you want to copy
        ObjCopied.Property1 = ObjOriginal.Property1
        Return ObjCopied 
    End Function
'other property & methods...
End Class



现在......而不是你的代码......


Now... instead of your code...

Dim Xglobal as new NameClass
Dim Xlocal as new NameClass
XLocal = XGlobal.Clone()



快乐编码!

:)


Happy Coding!
:)


这篇关于复制类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆