我知道这个问题有几个标准答案(我以前成功使用过!)请参见https://dev59.com/d3I-5IYBdhLWcg3wlpeW#1778410和https://dev59.com/eXI_5IYBdhLWcg3wAeLl#1565766。这些方法涉及使用属性的
考虑以下内容:
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 中的初始化器 setter。无论是在 .NET 4.5 还是 .NET Core 2 运行时中都会失败。我错过了什么吗?
Example
类是在另一个程序集中吗? - DavidG