我可以使用反射更改C#中的私有只读继承字段吗?

我可以使用反射更改C#中的私有只读继承字段吗?,c#,reflection,inheritance,superclass,C#,Reflection,Inheritance,Superclass,就像在java中一样,我有: Class.getSuperClass().getDeclaredFields() 如何从超类中知道并设置私有字段 我知道这是强烈不推荐的,但我正在测试我的应用程序,我需要模拟一个错误的情况,其中id是正确的,名称不是。但此Id是私有的。此类将允许您执行以下操作: 用法: new PropertyType(this.GetType(), "_myParentField").SetValue(this, newValue); 顺便说一句,它将在公共/非公共字段或

就像在java中一样,我有:

Class.getSuperClass().getDeclaredFields()
如何从超类中知道并设置私有字段


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

此类将允许您执行以下操作:

用法:

new PropertyType(this.GetType(), "_myParentField").SetValue(this, newValue);
顺便说一句,它将在公共/非公共字段或属性上工作。为了便于使用,您可以像这样使用派生类:

new PropertyValue<int>(this,  "_myParentField").Value = newValue;
newpropertyvalue(这个,“\u myParentField”)。Value=newValue;

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

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

fi.SetValue(this, 1);
编辑

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

是的,你可以

对于字段,请使用
FieldInfo
类。
BindingFlags.NonPublic
参数允许您查看私有字段

public class Base
{
    private string _id = "hi";

    public string Id { get { return _id; } }
}

public class Derived : Base
{
    public void changeParentVariable()
    {
        FieldInfo fld = typeof(Base).GetField("_id", BindingFlags.Instance | BindingFlags.NonPublic);
        fld.SetValue(this, "sup");
    }
}
还有一个小测试来证明它的有效性:

public static void Run()
{
    var derived = new Derived();
    Console.WriteLine(derived.Id); // prints "hi"
    derived.changeParentVariable();
    Console.WriteLine(derived.Id); // prints "sup"
}

正如JaredPar所建议的,我做了如下工作:

//to discover the object type
Type groupType = _group.GetType();
//to discover the parent object type
Type bType = groupType.BaseType;
//now I get all field to make sure that I can retrieve the field.
FieldInfo[] idFromBaseType = bType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

//And finally I set the values. (for me, the ID is the first element)
idFromBaseType[0].SetValue(_group, 1);

感谢大家。

+1用于csharptest网络库。它有一个有趣的记录器。您确定idFromBaseType[0]是正确的字段吗?您可能应该按名称匹配…对我来说是可行的,因为我的第一个元素是ID。但我尝试使用字符串获取字段,但没有成功。现在,为什么我只能使用“k__BackingField”获取字段?