通过反射在 属性 上设置私有 setter

Set private setter on property via reflection

我知道这有几个规范的答案(我过去曾成功使用过!)请参阅 and 。作为参考,这些方法涉及在 属性 的 PropertyInfo 上使用 SetValue 方法,或者通过反射调用 setter 方法,或者在极端情况下,设置 backing直接打野。然而,这些方法中的 none 现在似乎对我有用,我很好奇是否有什么改变破坏了这个功能。

考虑以下因素:

using System;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        var exampleInstance = new Example();
        var exampleType = typeof(Example);
        var fooProperty = exampleType.GetProperty("Foo"); // this works fine - the "GetSetMethod" method returns null, however

        // fails with the following:
        // [System.MethodAccessException: Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.]
        //fooProperty.SetValue(exampleInstance, 24);

        // same error here:
        //Run-time exception (line 14): Attempt by method 'Program.Main()' to access method 'Example.set_Foo(Int32)' failed.
        //exampleType.InvokeMember(fooProperty.Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.SetProperty | BindingFlags.Instance, null, exampleInstance, new object[] { 24 });
    }
}

public class Example 
{
    public int Foo { get; private set; }
}

Foo属性一个setter,只是私人的。如果我将 setter 更改为 protected,它也会失败,这看起来更奇怪,因为它不再是仅 C#6 初始化器 setter。 .NET 4.5 和 .NET Core 2 作为运行时都失败了。我错过了什么?

此行为是设计使然。 有一些严格的规则来管理以这种方式滥用反射的能力。

Accessing Members That Are Normally Inaccessible

事实上,如果您打算完全使用反射,那么在现实生活中,整篇文章都值得一读。 Security Considerations for Reflection

我遇到了类似的问题(除了我使用的是静态 属性)并且我能够像这样调用私有 setter:

public static class Example 
{
    public static int Foo { get; private set; }
}

typeof(Example).GetProperty("Foo").SetMethod.Invoke(null, new object[] { 42});

不过还没有用非静态测试过。