Since record
type is immutable, a new instance is created whenever a property is set
My question is: using reflection, is it possible to set values to multiple properties without creting new instance on every assignment (same as with
reserved word)?
Thank you!
public class Program
{
public record Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public static void Main()
{
var p = new Person();
Console.WriteLine("Hashcode BEFORE property assignment: " + p.GetHashCode());
var pis = p.GetType().GetProperties( BindingFlags.Instance | BindingFlags.Public);
foreach (var pi in pis)
{
pi.SetValue(p, "f"); //this line creates and assign a new instance (record is immutable)
Console.WriteLine($"Hashcode AFTER \'{pi.Name}\' property assignment: " + p.GetHashCode());
}
}
}
Aucun commentaire:
Enregistrer un commentaire