lundi 12 juillet 2021

Set Property of Instance without Setter [duplicate]

Suppose I have a class and an interface that looks like this:

[Serializable]
public class MyClass : IClass
{
   public int Prop => 42;
}

public interface IClass
{
   int Prop { get; }
}

As you can see there's no Setter. But I was hoping to use reflection to change the Prop property but I can't seem to do it. Here's what I have so far:

var property = typeof(MyClass).GetProperty("Prop", BindingFlags.Instance | BindingFlags.Public);
property.SetValue(instaneOfClass, 31);

I keep getting this error: System.ArgumentException: Property set method not found.

Shouldn't this work? How can I set the property without using a setter?





Aucun commentaire:

Enregistrer un commentaire