vba - vba中的面向对象编程和卷影复制问题
问题描述
我最近正在研究一个基于 VBA 的大型项目,该项目需要构建许多类。突然发现set object = other object默认是shadow copy,这是我继续下去的最大问题。我需要使用对象来初始化其他对象并在对象内部更改这些对象,但不希望更改原始对象。在其他语言中,如 C++,这很容易实现,只需在对象内部创建一个成员变量并进行深度复制。但是,在 vba 中,设置对象时默认设置卷影副本。我在网上搜索了很多资源,这些资源教你如何手动进行深度复制,我认为这对于较小的项目来说很好。我的代码中有大量这种逻辑需要我实现深拷贝。
实际上我不想问如何在对象方面进行深度复制,因为我认为资源已经教会了我。我只是问你什么时候需要在 vba 中做一个需要使用很多类的大项目。您如何处理此类问题?
我尽量举个例子
Class Risk ' for simplification, just let Risk has one member variable and it's public so i don't need to write another method in order to change the value
public value as double
Class Profile
dim reportingRisks As Collection ' is a collection of a class risk
dim profileShocks As Collection
sub init() 'this is used to initialize the member variables like reportingRisks in class Profile
...
end sub
Class Asset
Dim reportingRisks as Collection
Dim profileShocks as Collection
sub init(aProfile as Profile, str as string) ''this is used to initialize the member variables in Asset class, in this part, we need to use information both in aProfile and str to initialize and we want aProfile are same each time, str would be different
set reportingRisks = aProfile.reportingRisks
' then based on the information from str, the element in the reportingRisks would change
reportingRisks(0).value = cint(str)
end sub
'Then in the main sub
sub main()
dim assets as new collection
dim theProfile as new Profile
theProfile.init
dim str as variant
str = readsomefile() ' assume this str is assigned by reading the a multiple lines file and it becomes a array, each element is a number
dim temp as variant
dim ass as Asset
for each temp in str
set ass = new Asset
ass.init theProfile, temp ' I pass theProfile into this Procedure, and cause the temp is different, so the element in theProfile like reportingRisks will change everytime, but I don't want it change.
assets.add ass
next temp
end sub
而且,这只是一个非常简化的示例,在项目中有大量此类程序,我不希望原始参数因函数或子函数内部的参数更改而更改,例如reportingRisk(0).value =辛特(字符串)。你有什么建议吗?可能我构造代码的方式是错误的。
解决方案
推荐阅读
- c# - 带有迭代器方法的 MarshalByRefObject (IEnumerable
) 不工作 - spring-boot - Spring Boot 自定义验证器自动装配字段为空
- php - preg_match_all 疑难解答
- pagespeed - 有没有人在使用 Google pagespeed 测试 TypeError 时遇到错误:无法读取未定义的属性“长度”
- android - ViewBinding GeneratedCode 在哪里
- php - PHP Guzzle:cURL 错误 52:来自服务器的空回复 - 可能是什么原因?
- jenkins-pipeline - 是否可以访问詹金斯管道中不同节点/代理上的全局变量?
- c++ - 我在使用 switch、break、case 语法时遇到了一些问题
- windows - 为什么调用内存密集型 Rust 函数会导致 Windows 上的 main 堆栈溢出,而不是在测试中?
- vue.js - Vue jsx,渲染函数中的h已定义但从未使用过