【发布时间】:2021-09-22 00:51:54
【问题描述】:
假设我有一个如下所示的类和接口:
[Serializable]
public class MyClass : IClass
{
public int Prop => 42;
}
public interface IClass
{
int Prop { get; }
}
如您所见,没有 Setter。但我希望使用反射来改变 Prop 属性,但我似乎做不到。到目前为止,这是我所拥有的:
var property = typeof(MyClass).GetProperty("Prop", BindingFlags.Instance | BindingFlags.Public);
property.SetValue(instaneOfClass, 31);
我不断收到此错误:System.ArgumentException: Property set method not found.
这不应该吗?如何在不使用 setter 的情况下设置属性?
【问题讨论】:
-
我将其作为先前建议答案的副本关闭,因为它已经包含文本“复杂代码”。我还编辑了答案以添加“复杂代码包括
int TheAnswer => 42;,因此它也清楚地回答了这个问题。 -
剩下的谜团是:值 '42' 的 int 存储在哪里?
标签: c# .net reflection