像在Java中一样:

Class.getSuperClass().getDeclaredFields()

如何从超类中了解并设置私有字段?

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

有帮助吗?

解决方案

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

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"
}

这门课可以让你这样做:

http://csharptest.net/browse/src/Library/Reflection/PropertyType.cs

用法:

new PropertyType(this.GetType(), "_myParentField").SetValue(this, newValue);

BTW,它适用于公共/非公共领域或财产。为了便于使用,您可以使用派生类 PropertyValue ,如下所示:

new PropertyValue<int>(this,  "_myParentField").Value = newValue;

就像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);

感谢所有人。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top