mercredi 11 décembre 2019

PropertyInfo.SetValue doesn't work when the property in a base class doesn't have a setter

I am using reflection to get objects. Initially I created a class with an "Id" property without a setter because I don't want the user of the framework to set a value to the Id property:

public class Client {
    public int? Id { get; private set; }
    public string Name { get; set; }
    public string Email { get; set; }

    public Client(string name, string email) {
        Id = null;
        Name = name;
        Email = email;
    }
}

Using reflection I am able to set a value to the Id property using the following code:

foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
    if (prop.Name == "Id") {
       prop.SetValue(obj, id);
       break;
    }
}

But when I use inheritance the PropertyInfo.SetValue doesn't work for the Id property:

public abstract class Client {
    public int? Id { get; private set; }
    public string Name { get; set; }
    public string Email { get; set; }

    public Client(string name, string email) {
        Id = null;
        Name = name;
        Email = email;
    }
}

public class PhysicalPerson : Client {
        public string CPF { get; set; }
        public DateTime BirthDate { get; set; }

        public PhysicalPerson(string name, string email, string cpf, DateTime birthDate) : base(name, email) { 
            CPF = cpf;
            BirthDate = birthDate;
        }
    }

When prop.SetValue is executed, it returns the exception "Property set method not found". I know the Id property doesn't have a setter, but why it works when there is no inheritance? I really want to keep the Id property without a setter. Does anyone know how to circunvent this situation?





Aucun commentaire:

Enregistrer un commentaire