使用按值传递还是按引用传递?

时间:2018-10-30 19:43:44

标签: c# pass-by-reference pass-by-value

我的代码中有两种方法。以下是其中之一。

 private async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
    {
        var newValue = FormatValueByPresentation(args.CharacteristicValue, presentationFormat);
        var message = $"Value at {DateTime.Now:hh:mm:ss.FFF}: {newValue}";
        await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
            () => CharacteristicLatestValue.Text = message);
    }

它的打印时间(值At)像this.

现在,这是第二种方法。

 private static ushort ParseHeartRateValue(byte[] data)
    {

        const byte heartRateValueFormat = 0x04;

        byte flags = data[0];
        ushort offset = 1;

        bool HRC2 = (flags & 0x80) > 0; 

        if (HRC2) //if BPM is un uint16
        {
            short hr = BitConverter.ToInt16(data, offset);
            offset += 2;
            System.Diagnostics.Debug.WriteLine("We have 16:" + hr.ToString("x"));

        }
        else // if BPM is uint8
        {
            byte hr = data[offset];
            offset += 1;
            System.Diagnostics.Debug.WriteLine("no 16:" + hr.ToString("x"));
        }



        bool ee = (flags & (1 << 3)) != 0;
        if (ee)
            offset += 2;



        // bool rr = ((flags & 1 << 4) != 0);
        bool rr = ((flags & 0x10) != 0);
        if (rr)
        {
            int count = (data.Length - offset) / 2;
            for (int i = 0; i < count; i++)
            {


                ushort value = BitConverter.ToUInt16(data, offset);

                intervals.Add((double)value); // Added
                if (intervals.Count > 190) // Added
                    intervals.RemoveAt(0);// Added 
                double mean = intervals.Average();// Added
                double sumOfSquareDiff = intervals.Select(val => (val - mean) * (val - mean)).Sum(); // Added
                double vrHR = Math.Sqrt(sumOfSquareDiff / intervals.Count); // Added

                double intervalLengthInSeconds = value / 1024.0;
                offset += 2;

                System.Diagnostics.Debug.WriteLine("Heart Rate Variability:" + vrHR.ToString());
            }
        }

它正在打印输出,例如this.

但是,我希望将“心率变异性”打印在“ Value at”下方。 我该如何工作?

我应该按值或参考传递?还有其他建议吗?

我早些时候在Stack Overflow

问了更详细的问题

1 个答案:

答案 0 :(得分:2)

  

但是,我希望将“心率变异性”打印在“ Value at”下方。我该如何工作?

您的问题完全与“按价值或参考传递”无关。 CharacteristicLatestValue只是XAML页面上的TextBlock控件。它用于在UI上显示文本,如下所示:

Value at 01:11:25:453: Heart Rate: 124

如果您想显示'no 16:51','Heart Rate Variation:661841865028902'等,这些文字将如下所示:

Value at 01:11:25:453: Heart Rate: 124
no 16:51
Heart Rate Varibility:661841865028902

您只需要在CharacteristicLatestValue.Text之后添加它们,如下所示:

await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
        () => CharacteristicLatestValue.Text = "Value at 01:11:25:453: Heart Rate: 124"+"\r\n"+ "no 16:51"+"\r\n"+ "Heart Rate Varibility:661841865028902"+"\r\n");