我可以使用反射改变在C#中的私人只读字段? [英] Can I change a private readonly field in C# using reflection?
本文介绍了我可以使用反射改变在C#中的私人只读字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很纳闷,因为很多事情可以使用反射来完成,我可以改变一个私人只读域之后的构造完成执行?结果
(注:只是好奇)
公共类Foo
{
私人只读INT吧; 公共美孚(INT NUM)
{
巴= NUM;
} 公众诠释GetBar()
{
返回酒吧;
}
}富富=新的Foo(123);
Console.WriteLine(foo.GetBar()); //显示123
//反射code这里...
Console.WriteLine(foo.GetBar()); //显示456
解决方案
您可以:
typeof运算(富)
.GetField(酒吧,BindingFlags.Instance | BindingFlags.NonPublic可)
.SetValue(富,567);
I am wondering, since a lot of things can be done using reflection, can I change a private readonly field after the constructor completed its execution?
(note: just curiosity)
public class Foo
{
private readonly int bar;
public Foo(int num)
{
bar = num;
}
public int GetBar()
{
return bar;
}
}
Foo foo = new Foo(123);
Console.WriteLine(foo.GetBar()); // display 123
// reflection code here...
Console.WriteLine(foo.GetBar()); // display 456
解决方案
You can:
typeof(Foo)
.GetField("bar",BindingFlags.Instance|BindingFlags.NonPublic)
.SetValue(foo,567);
这篇关于我可以使用反射改变在C#中的私人只读字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文