c# - 在 C# 中,被移除对象的 Action 会发生什么?
问题描述
我想为我的类 TreeNode 制作一个深层副本。这是我的代码:
public TreeNode(TreeNode node, GUIStyle inPointStyle, GUIStyle outPointStyle, Action<ConnectionPoint> OnClickInPoint, Action<ConnectionPoint> OnClickOutPoint)
{
this.rect = new Rect(node.rect);
this.style = new GUIStyle(node.style);
this.inPoint = new ConnectionPoint(this, ConnectionPointType.In, inPointStyle, OnClickInPoint);
this.outPoint = new ConnectionPoint(this, ConnectionPointType.Out, outPointStyle, OnClickOutPoint);
this.defaultNodeStyle = new GUIStyle(node.defaultNodeStyle);
this.selectedNodeStyle = new GUIStyle(node.selectedNodeStyle);
this.allDecorations = new List<GameObject>(node.allDecorations);
this.objs = new Dictionary<GameObject, IndividualSettings>(node.objs);
this.name = String.Copy(node.name);
this.RemoveClonedObj = new Action(node.RemoveClonedObj);
this.OnChangeView = new Action<TreeNode>(node.OnChangeView);
this.OnRemoveNode = new Action<TreeNode>(node.OnRemoveNode);
this.OnCopyNode = new Action<TreeNode>(node.OnCopyNode);
this.PreviewTree = new Action<TreeNode, bool> (node.PreviewTree);
}
然而,骑士给了我警告:
骑士似乎在说我的“新”毫无意义。如果我按照 Rider 的指示,使用this.RemoveClonedObj = node.RemoveClonedObj;
删除原始 TreeNode 后复制的 TreeNode 的操作会发生什么?它们也会被删除吗?如果是这样,为什么 Rider 会给我这样的警告?
解决方案
在 C# 2.0 或更高版本中,以下代码是等效的(DelegateType
顾名思义,是委托类型):
newDelegate = new DelegateType(oldDelegate);
newDelegate = oldDelegate;
(请参阅MSDN - 如何:声明、实例化和使用委托(C# 编程指南))
此外,Microsoft 指定(参见此处)此类操作将始终创建 的新实例DelegateType
,该实例具有与oldDelegate
. 它们不引用同一个对象(不要被=
赋值混淆):
new D(E) 形式的 delegate_creation_expression 的绑定时处理,其中 D 是 delegate_type,E 是表达式,包括以下步骤:
如果 E 是方法组,则委托创建表达式的处理方式与从 E 到 D 的方法组转换(方法组转换)相同。
如果 E 是匿名函数,则委托创建表达式的处理方式与从 E 到 D 的匿名函数转换(Anonymous function conversions)相同。
如果 E 是一个值,则 E 必须与 D 兼容(委托声明),结果是对新创建的 D 类型委托的引用,该委托引用与 E 相同的调用列表。如果 E 与 D 不兼容,则会发生编译时错误。
所以关于你的问题
删除原始 TreeNode 后,我复制的 TreeNode 的操作会发生什么?它们也会被删除吗?
他们什么都不会发生。它们不会被删除。
顺便说一句,由于您正在尝试制作树节点的深层副本,我怀疑这是否是正确的方法。尽管您已经创建了委托的新实例,但与之关联的类实例(将在其上调用成员方法的实例)保持不变。
推荐阅读
- swift - 保护案例分配
- neural-network - 神经元网络的极端结构
- javascript - 在提交表单帖子之前获取 URL
- python-3.x - 如何使用除行(轴= 1)以外的参数将自定义函数传递给dataframe.apply
- arrays - Atollic TrueStudio (Eclipse) Debug Expressions 数组切割成零件
- python - 20newsgroup 数据集上的增强频率。TypeError:'int' 对象不可迭代
- javascript - 如何调试开发滑块以滚动浏览所有图像的错误?
- javascript - 如何将html id设置为变量
- python - 手势识别问题
- c++ - 如何在 Windows 10 操作系统上使用 Bazel 调试 c++ 代码