首页 > 解决方案 > 如何访问元组的索引值?

问题描述

考虑另一个 StackOverflow 问题中的以下代码:

public (double, string) AdjustFileSize(long fileSizeInBytes)
{
    var names = {"BYTES", "KB", "MB", "GB"};

    double sizeResult = fileSizeInBytes * 1.0;
    int nameIndex = 0;
    while (sizeResult > 1024 && nameIndex < names.Length)
    {
        sizeResult /= 1024; 
        nameIndex++;
    }

    return (sizeResult, names[nameIndex]);
}

我对元组不了解的是,我觉得在调用方法中我应该能够取回 KB、MB 或 GB 值。但是,我不知道怎么做。

FileSize = filesize.Item1.ToString("F"),

我得到的只是 KB 文件大小值,我如何访问其他数值?

标签: c#tuples

解决方案


Function returns only one size for one appropriate unit.

how do I access the other numeric values?

Change function to return size for all units

public class FileSize
{
    private readonly double _bytes;

    public double Bytes => _bytes;
    public double Kb => _bytes / 1024;
    public double Mb => Kb / 1024;
    public double Gb => Mb / 1024;

    public FileSize(long size)
    {
        _bytes = size * 1.0
    }
}

// Usage

var size = new FileSize(120000);
size.Bytes; // 120000
size.Kb; // 120
size.Mb; // 0.12

I would suggest to use class to encapsulate behaviour with associated value.


推荐阅读