简体   繁体   中英

How to initialize get-only property C#

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:

  • check for parameters in all constructors
  • check for public setter methods
  • if you have access to source code, check for Address references (maybe the original purpose was something completely different and there is a reason why its setter is restricted)
  • contact author
  • reflection
//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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM