I have a class like this:
public class Customer
{
public int Id { get; set; }
public string FullName { get; set; }
public string Address{ get; }
}
How may I initialize an instance of this class and setup the 'Address' get-only property value? I've tried with
var customer = new Customer
{
Id = 228,
FullName = "Peter",
Address = "Kreshatik",
};
but it it doesn't work.
Please, note that it's not my class and I have no ability to change anything there.
Absolutely agree with previous answer by @rfmodulator, under given circumstances reflection is the only possible solution. My steps to resolve this issue would be:
//using System.Reflection;
var backingField = typeof(Customer).GetField("<Address>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance);
var customer = new Customer
{
Id = 228,
FullName = "Peter",
};
backingField.SetValue(customer, "Kreshatik");
If backingField
is null you'll need to dig deeper with reflection to find it.
You can use GetFields(...)
with the same flags to list them.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.