如果两个类具有相同的键(它只是一个字符串),我希望两个类共享一个对象,因此如果对象的值发生变化,它在两个类中都会发生变化。我认为这就像让两个对象指向同一个内存地址,所以在 C 中可以用指针来完成。为了澄清我想要做什么,我准备了下一个示例代码:
class MyObject
{
string key;
int value;
public MyObject(string key, int value)
{
this.key = key;
this.value = value;
}
}
class MainClass{
MyObject parameter = new MyObject("key", 5);
List<MyObject> list = new List<MyObject>();
list.Add(parameter);
}
class SecondaryClass{
MyObject parameter = new MyObject("key", 0);
List<MyObject> list = new List<MyObject>();
list.Add(parameter);
}
MainClass mainClass = new MainClass();
SecondaryClass secondaryClass = new SecondaryClass();
foreach (MyObject newParameter in mainClass.list)
{
// Try to find a match in the parameterKey
MyObject parameter = secondaryClass.list.Find(p => p.Key == newParameter.Key);
// If there is a match, update the object
if (parameter != null)
{
parameter = newParameter;
}
}
Console.WriteLine(mainClass.parameter.value) // This output 5
Console.WriteLine(secondaryClass.parameter.value) // This output 0
看到 secondaryClass 的参数仍然指向 0,值还没有更新。在 C# 中可以做到这一点吗?也许分享引用?
--- 编辑 ---
我现在按照 Jon Skeet 的要求提供了一个最小、完整且可验证的示例。
class MyObject
{
public string key;
public int value;
public MyObject(string key, int value)
{
this.key = key;
this.value = value;
}
}
class MainClass
{
public MyObject parameter = new MyObject("key", 5);
public List<MyObject> list = new List<MyObject>();
public MainClass()
{
list.Add(parameter);
}
}
class SecondaryClass
{
public MyObject parameter = new MyObject("key", 0);
public List<MyObject> list = new List<MyObject>();
public SecondaryClass()
{
list.Add(parameter);
}
}
class Program
{
static void Main(string[] args)
{
MainClass mainClass = new MainClass();
SecondaryClass secondaryClass = new SecondaryClass();
foreach (MyObject newParameter in mainClass.list)
{
// Try to find a match in the parameterKey
MyObject parameter = secondaryClass.list.Find(p => p.key == newParameter.key);
// If there is a match, update the object
if (parameter != null)
{
parameter = newParameter;
}
}
Console.WriteLine(mainClass.parameter.value); // This output 5
Console.WriteLine(secondaryClass.parameter.value); // This output 0, I expected 5
mainClass.parameter.value = 7;
Console.WriteLine(mainClass.parameter.value); // This output 7
Console.WriteLine(secondaryClass.parameter.value); // This output 0, I expected 7
}
}
如您所见,对象 secondaryClass.parameter 没有更改,仍然指向原始对象。当然,如果它只是一个对象,我可以在末尾添加这两行:
secondaryClass.parameter = mainClass.parameter;
mainClass.parameter.value = 9;
Console.WriteLine(mainClass.parameter.value); // This output 9
Console.WriteLine(secondaryClass.parameter.value); // This output 9
有两个主要问题:
MyObject 比此处显示的更复杂,包含更多 里面的属性。
MainClass和SecondaryClass有多个对象MyObject,只有具有相同 key 的对象才需要共享(并且两个类都可以有不共享的MyObject对象)。
最佳答案
使用parameter = newParameter
,您仅修改MyObject参数
的引用,这是一个局部变量。
您没有修改 secondaryClass 列表中对象的引用。
关于c# - 在 C# 中的类之间共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55261455/