简体   繁体   中英

How to Init get-only properties in C#

I've made a class called Device which has the following properties:

public int Id { get; }
public string DeviceName { get; set; }
public string MACAddress { get; set; }
public string UUID { get; set; }
public string SerialNumber { get; set; }
public string Location { get; set; }
public string PinCode { get; }

I use these properties to get information from my database.

I then want to update the device in my database using the following:

private void _updateDeviceInDataBase()
{
    DataAccess database = new DataAccess();
    Device device = new Device()
    {
        DeviceName = textBox_PcNumber.Text,
        SerialNumber = DeviceProperties.GetSerialNumber(),
        UUID = DeviceProperties.GetUUID(),
        MACAddress = DeviceProperties.GetMACAddress(),
        Location = comboBox_Location.Text,
    };

    database.UpdateDevice(device);
}

My problem is, that my Id and my PinCode is null, because I obviously don't set them in my device variable.

My question then is - how do I make use of the properties Id and PinCode in my device , without having to change them to set ?

You can init get-only properties in the constructor..

public class Device
{
    public int Id { get; }
    public string DeviceName { get; set; }
    public string MACAddress { get; set; }
    public string UUID { get; set; }
    public string SerialNumber { get; set; }
    public string Location { get; set; }
    public string PinCode { get; }

    public Device(int id, string pinCode)
    {
        Id = id;
        PinCode = pinCode;
    }
    // other code ...
    // public Device(){} // uncomment this if you want to call new Device();
}

If initiating Id, PinCode properties is not required, you can uncomment // public Device(){} line.

Thanks to @Franck comment, you can set Id, PinCode properties via setter injection

public class Device
{
    public int Id { get; private set; }
    public string DeviceName { get; set; }
    public string MACAddress { get; set; }
    public string UUID { get; set; }
    public string SerialNumber { get; set; }
    public string Location { get; set; }
    public string PinCode { get; private set;}
    
    public void SetId(int id) => Id = id;
    public void SetPinCode(string pinCode) => PinCode = pinCode;

    // other code ...
}

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