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

NWa*_*ard 6 c# reflection c#-7.2

我知道这有几个规范的答案(我过去成功使用过!)请参阅/sf/answers/124488731//sf/answers/109603651/。作为参考,这些方法包括使用SetValue上的方法PropertyInfo的属性的,或以其他方式调用setter方法用的反射,或在极端情况下,直接设置支持字段。但是,这些方法现在似乎都不适合我,我很好奇是否发生了破坏此功能的更改。

考虑以下:

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; }
}
Run Code Online (Sandbox Code Playgroud)

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

use*_*226 1

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

访问通常无法访问的成员

事实上,如果您打算使用反射,那么在现实生活中,整篇文章可能值得一读。 反思的安全考虑