Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/324.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#反射不';你不能用Point类吗?_C#_Reflection_Properties_Point - Fatal编程技术网

C#反射不';你不能用Point类吗?

C#反射不';你不能用Point类吗?,c#,reflection,properties,point,C#,Reflection,Properties,Point,我不知道我做错了什么。我有这个密码: Point p = new Point(); //point is (0,0) p.X = 50; //point is (50,0) PropertyInfo temp = p.GetType().GetProperty("X"); temp.SetValue(p, 100, null); //and point is still (50,0) MethodInfo tt = temp.GetSetMethod(); tt.Invoke(p, new ob

我不知道我做错了什么。我有这个密码:

Point p = new Point();
//point is (0,0)
p.X = 50;
//point is (50,0)
PropertyInfo temp = p.GetType().GetProperty("X");
temp.SetValue(p, 100, null);
//and point is still (50,0)
MethodInfo tt = temp.GetSetMethod();
tt.Invoke(p, new object[] { 200 });
//still (50,0)
为什么?


我一直在寻找答案,但什么也没找到。

点是一个结构,而不是一个类。它是一个值类型及其传递的值。所以,当您将点传递给
SetValue
方法时,将传递点的副本。这就是原始实例
p
未更新的原因


建议阅读:

啊,可变结构的乐趣。正如谢尔盖所说,
是一个结构。调用
PropertyInfo.SetValue
时,获取
p
的值,将其装箱(复制该值),修改框的内容。。。但随后就忽略了它

您仍然可以对其使用反射,但重要的是,您只想将其框起一次。所以这是可行的:

object boxed = p;
PropertyInfo temp = p.GetType().GetProperty("X");
temp.SetValue(boxed, 100, null);
Console.WriteLine(boxed); // {X=100, Y=0}
MethodInfo tt = temp.GetSetMethod();
tt.Invoke(boxed, new object[] { 200 });
Console.WriteLine(boxed); // {X=200, Y=0}
请注意,这不会更改
p
的值,但您可以在以后再次取消装箱:

object boxed = p;
property.SetValue(boxed, ...);
p = (Point) boxed;

或者你可以使用
RuntimeHelpers.GetObjectValue(p)
来控制调用
SetValue
@KonradKokosa时的装箱:嗯,可能:)我不能说我自己用过,我不确定它在这里有什么用处……我知道这几乎是显而易见的。非常感谢你们。