简体   繁体   中英

Byte array Properties C#

I have an object like this:

public class CustomObject{

    public byte[] FieldA {private get; set;}
    public IPAddreess FieldB {private get; set;}

}

FieldA is the byte rappresentation of FieldB.

I create this object from two sources of data. One from a binary file where i need to be fast, then i prefer to set only the FieldA. The other one is in an application where i retrieve the data only in "FieldB format".

I want a function like this:

public IPAddress GetField(){
   if (FieldB != null)
       return FieldB;
   FieldB = new IPAddress(FieldA);
   return FieldB;
}

To simplify i used an IPAddress conversion, but usually i have more complex operations to do.

Is this the correct way to do this? Or there is some other method that can simplify this one? I'm using .NET CORE Thank you in advance

You can do that in FieldB 's getter, without explicitly writing a get-method:

private IPAddreess _fieldB;
public IPAddreess FieldB 
{
    get
    {
        if (_fieldB == null)
        {
            _fieldB = new IPAddress(FieldA);
        }
        return _fieldB;
    }
    set
    {
        _fieldB = value;
    }
}

This code uses a private backing field _fieldB for storing the property's value. Upon retrieving the property, it'll either return the value already stored in the field, or assign it based on FieldA 's contents and then return it.

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