我有一小段代碼將節點分配給名為 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# 中一樣創建函式?如果是這樣,我如何將這樣的參考傳遞給這樣的欄位?
uj5u.com熱心網友回復:
使用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,它允許您在其原始位置重新分配傳遞的實體。
這列印
開始一個 開始 b 修改了!? 修改了b!?
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449497.html
標籤:C#
上一篇:我該如何解決這個for回圈程式?
