我有一小段代码将节点分配给名为 NodeA 和 NodeB 的字段。但是代码相当重复,所以感觉我可以将它简化为一个函数。但我想知道是否可以引用类中的实际字段以分配给特定字段?
我的字段/属性设置如下:
public class Test {
private Node _nodeA;
private Node _nodeB;
public void Set(Node nodeA, Node nodeB){
if (_nodeA != null)
_nodeA.OnChange -= Update;
_nodeA = nodeA;
_nodeA.OnChange += Update;
if (_nodeB != null)
_nodeB.OnChange -= Update;
_nodeB = nodeB;
_nodeB.OnChange += Update;
}
void Update(){}//todo
}
我想把它放到一个简单的函数中,这样我就可以传入节点,但也可以传递一个指向我想要分配给它的字段的引用......沿着这个想法(伪代码)
Set(Node node, /* pointer to _nodeA or _nodeB */ ptr)
{
if(ptr != null) ptr.OnChange -= Update;
ptr = node;
ptr.OnChange += Update;
}
Set(nodeA, /* pointer to field _nodeA */ );
Set(nodeB, /* pointer to field _nodeB */ );
Set
是否可以像在 C# 中一样创建函数?如果是这样,我如何将这样的引用传递给这样的字段?
使用ref
关键字。这样您就可以更改基础分配。
这是一个简化版本:
using System;
public class Program
{
public static void Main()
{
// print the original node values
Console.WriteLine(Test._nodeA.Message);
Console.WriteLine(Test._nodeB.Message);
// modify the two nodes using a brand new instance
Test.Set(ref Test._nodeA, new Node { Message = "modified a" });
Test.Set(ref Test._nodeB, new Node { Message = "modified b" });
// print out the new node data
Console.WriteLine(Test._nodeA.Message);
Console.WriteLine(Test._nodeB.Message);
}
}
public static class Test
{
// these need to be public so that the code CALLING "Set" can use these fields
public static Node _nodeA = new Node { Message = "start a" };
public static Node _nodeB = new Node { Message = "start b" };
public static void Set(ref Node target, Node newVal)
{
// all this does is simple reassignment, but it's to the
// same reference location in memory that _nodeA/_nodeB holds.
// you can add more complex logic as well.
target = newVal;
// because target and newVal have the same memory ref
// you can modify them interchangeably and they effect each other
target.Message += "!";
newVal.Message += "?";
}
}
public class Node
{
public string Message {get;set;}
}
该Set
方法的第一个参数使用ref
,它允许您在其原始位置重新分配传递的实例。
这打印
开始a 开始b 修改a!? 修改了b!?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句