[英]Set private setter on property via reflection
我知道這有幾個規范的答案(我過去成功使用過!)請參閱https://stackoverflow.com/a/1778410/1675729和https://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.