简体   繁体   English

字节数组属性C#

[英]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. FieldA是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. 一个来自二进制文件,我需要快速,然后我更喜欢只设置FieldA。 The other one is in an application where i retrieve the data only in "FieldB format". 另一个是在我仅以“ FieldB格式”检索数据的应用程序中。

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. 为简化起见,我使用了IPAddress转换,但是通常我要执行更复杂的操作。

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 我正在使用.NET CORE预先感谢您

You can do that in FieldB 's getter, without explicitly writing a get-method: 您可以在FieldB的getter中执行此操作,而无需显式编写get方法:

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. 此代码使用私有后备字段_fieldB来存储属性的值。 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. 检索属性后,它要么返回已经存储在字段中的值,要么根据FieldA的内容进行分配,然后返回它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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