簡體   English   中英

通過反射在屬性上設置私有 setter

[英]Set private setter on property via reflection

我知道這有幾個規范的答案(我過去成功使用過!)請參閱https://stackoverflow.com/a/1778410/1675729https://stackoverflow.com/a/1565766/1675729 作為參考,這些方法涉及在PropertyInfo上使用SetValue方法,或者通過反射調用 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; }
}

Foo屬性一個 setter,它只是私有的。 如果我將 setter 更改為protected ,它也會失敗,這看起來更奇怪,因為它不再是 C#6 初始值設定項。 這在 .NET 4.5 和 .NET Core 2 作為運行時失敗。 我錯過了什么?

此行為是設計使然。 有一些嚴格的規則控制以這種方式濫用反射的能力。

訪問通常無法訪問的成員

事實上,如果您打算使用反射,在現實生活中,整篇文章可能值得一讀。 反射的安全注意事項

我遇到了類似的問題(除了我使用的是靜態屬性),我能夠像這樣調用私有 setter:

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

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

還沒有用非靜態測試過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM