关于ref传值的一个新问题:难!!!在线讨论。。。
先给个例子:
using System;
public class MyClass
{
public static void TestRef(ref char i)
{
char c = i ;
c = 'b';
}
public static void TestNoRef(char i)
{
i = 'c';
}
public static void Main()
{
char i = 'a'; // variable must be initialized
TestRef(ref i); // the arg must be passed as ref
Console.WriteLine(i);
TestNoRef(i);
Console.WriteLine(i);
Console.ReadLine() ;
}
}
可知ref传值要想修改原值则只能在函数体内。
实际问题是这样的:我有一个窗体用来修改对象的信息,直接在窗体中进行修改可以反映到对象,
但是,我有保存到文件和从文件读取对象信息的功能,在从文件中读取对象信息时,我是通过序列化
将对象还原的,这势必产生一个新对象这样配置信息就不能传递到原值中去,甚是郁闷!
例如:
C为配置信息类
A中需要配置信息c
B为修改配置信息的窗体
test函数为从文件中反序列化出配置信息,在此做了简化
public class C
{
string name ;
public C(string name)
{
this.name = name ;
}
}
public class A
{
C c = new C("A") ;
}
public class B
{
C c;
public B(ref C c)
{
this.c = c ;
}
public void Test()
{
c = new C("test") ;
}
public static void Main()
{
A a = new A() ;
Console.WriteLine(A.c.name);
B b = new B(ref A.c) ;
B.test() ;
Console.WriteLine(A.c.name);
Console.ReadLine() ;
}
}
结果为: A
A
怎么样才能让反序列化出来的配置信息反映到原对象中????、