c# - 如何访问元组的索引值?
问题描述
考虑另一个 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 文件大小值,我如何访问其他数值?
解决方案
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.
推荐阅读
- java - 如何将包信息与 Byte-buddy 中的类相关联?
- reactjs - Expo / React Native - 登录后无法重定向到主屏幕
- r - 在R中的多维数组中删除一层命名
- node.js - 更新电子和打字稿后的电子问题
- c# - 如何使用 C# 选择特定范围的数据列
- database - 如何使用 AppScript 将日期(从谷歌表数据)转换为时间戳(Firestore)?
- react-native-firebase - 无法使用 react-Native-firebase 构建项目
- javascript - 计算器应用程序中的日语数字格式
- rust - 如何确保 self 在不借入的情况下超过返回值
- go - 同时扫描多个端口时结果不可靠