首页 > 解决方案 > 在 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#unity3drider

解决方案


在 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 的操作会发生什么?它们也会被删除吗?

他们什么都不会发生。它们不会被删除。


顺便说一句,由于您正在尝试制作树节点的深层副本,我怀疑这是否是正确的方法。尽管您已经创建了委托的新实例,但与之关联的类实例(将在其上调用成员方法的实例)保持不变。


推荐阅读