我可以使用反射更改C#中的私有只读继承字段吗? [英] Can I change a private readonly inherited field in C# using reflection?

查看:387
本文介绍了我可以使用反射更改C#中的私有只读继承字段吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像我在java中一样:

like in java I have:

Class.getSuperClass().getDeclaredFields()

我如何知道并从超类中设置私有字段?

how I can know and set private field from a superclass?

我知道这是强烈不推荐的,但我正在测试我的应用程序,我需要模拟一个错误的情况,其中id是正确的,而名称不是。但是这个Id是私有的。

I know this is strongly not recommended, but I am testing my application and I need simulate a wrong situation where the id is correct and the name not. But this Id is private.

推荐答案

是的,可以使用反射来设置构造函数之后的只读字段的值已经运行

Yes, it is possible to use reflection to set the value of a readonly field after the constructor has run

var fi = this.GetType()
             .BaseType
             .GetField("_someField", BindingFlags.Instance | BindingFlags.NonPublic);

fi.SetValue(this, 1);

编辑

已更新以查看直接父类型。如果类型是通用的,则此解决方案可能会出现问题。

Updated to look in the direct parent type. This solution will likely have issues if the types are generic.

这篇关于我可以使用反射更改C#中的私有只读继承字段吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆