下面的是一个例子: class Class1 { [STAThread] static void Main(string[] args) { class2 c1 = new class2(); c1.I = 10; test1 t1 = new test1(); ArrayList al = new ArrayList(); al.Add(t1); foreach(PropertyInfo info in c1.GetType().GetProperties()) { PropertyInfo tinfo = al[0].GetType().GetProperty(info.Name); tinfo.SetValue(al[0],info.GetValue(c1,null),null); } Console.WriteLine(t1.I); Console.WriteLine(((test1)al[0]).I); Console.ReadLine();
} } struct test1 { private int i; public int I { get{return this.i;} set{this.i = value;} } private int j; float k; } class class2 { private int i; public int I { get{return this.i;} set{this.i = value;} } private int j; float k; }我发现一个问题,如果把t1做装箱处理,则Reflection是可以工作的 但是如果直接操作t1,那么reflection不工作,感觉超级奇怪。 继续研究中
起码效率上比较高
当然,你可以通过诸如反射之类的技术来搞定这个问题
对类(某个实例)的属性做一个foreach循环,取出属性,放到结构里面。
7饭回来retry
class Class1
{
[STAThread]
static void Main(string[] args)
{
class2 c1 = new class2();
c1.I = 10; test1 t1 = new test1(); ArrayList al = new ArrayList();
al.Add(t1); foreach(PropertyInfo info in c1.GetType().GetProperties())
{
PropertyInfo tinfo = al[0].GetType().GetProperty(info.Name);
tinfo.SetValue(al[0],info.GetValue(c1,null),null); }
Console.WriteLine(t1.I);
Console.WriteLine(((test1)al[0]).I);
Console.ReadLine();
}
} struct test1
{
private int i;
public int I
{
get{return this.i;}
set{this.i = value;}
}
private int j;
float k;
} class class2
{
private int i;
public int I
{
get{return this.i;}
set{this.i = value;}
}
private int j;
float k;
}我发现一个问题,如果把t1做装箱处理,则Reflection是可以工作的
但是如果直接操作t1,那么reflection不工作,感觉超级奇怪。
继续研究中
但是如果直接操作t1,那么reflection不工作,感觉超级奇怪。
继续研究中因为SetValue的时候有拷贝和装箱,你所修改的只是一个SetValue的函数的局部变量的装箱。
俺也看到了SetValue这个方法的参数
.SetValue(object obj,object value.........)
这样一来,SetValue得到t1的时候,首先将其装箱,然后给其设值,然后这个装箱后的t1就木有了。
所以外面的结果0,是正确的
如果先将t1装箱,al.Add(t1)。再调用SetValue的时候,直接传递进去的就是一个object,所以SetValue不需要进行内部装箱,而t1的装箱之后的引用还在。
所以,结果是10,也是正确的。楼上一眼就看出问题
汗一个
class ClassA
{
char* str;
};这个时候对ClassA的实例进行值拷贝就会让两个实例拥有同样的指针,然后你再稀里糊涂的什么在析构函数里面delete掉str,就会调试到翻白眼……So对这些东西比较敏感一点儿……