gpt4 book ai didi

c# - 处理可变数量的输出参数,减少 C# 中的代码重复

转载 作者:IT王子 更新时间:2023-10-29 04:52:28 24 4
gpt4 key购买 nike

我正在尝试编写一个函数,用数组的内容填充字符串,或将它们设置为空。字符串的数量可能会有所不同,我不想添加要求,例如它们都属于同一数组或类。

在 C# 中,您不能组合 paramout .因此,唯一的方法似乎是重载这样的方法:

    public void ParseRemainders(string[] remainders, out string p1)
{
p1 = null;
if ((remainders != null) && (remainders.Length > 0))
p1 = remainders[0];
}

public void ParseRemainders(string[] remainders, out string p1, out string p2)
{
p1 = null;
p2 = null;
if (remainders != null)
{
ParseRemainders(remainders, out p1);
if (remainders.Length > 1)
p2 = remainders[1];
}
}

public void ParseRemainders(string[] remainders, out string p1, out string p2, out string p3)
{
p1 = null;
p2 = null;
p3 = null;
if (remainders != null)
{
ParseRemainders(remainders, out p1, out p2);
if (remainders.Length > 2)
p3 = remainders[2];
}
}

.... and on forever ....

如何避免所有这些代码重复,理想情况下接受任意数量的参数?


编辑:这很有用,因为你可以做,比方说,ParseRemainders(remainders, out inputFileName, out outputFileName, out configFileName)然后避免手动操作

if (remainder.Length > 0) inputFileName = remainder[0];
if (remainder.Length > 1) outputFileName = remainder[1];
if (remainder.Length > 2) configFileName = remainder[2];
...

抱歉,如果这不是很清楚,我有一个特定的目标,这就是为什么我不简单地返回一个 List<> .


结论:感谢 Botond Balázs 的回答,特别是暗示这称为“数组解构”。正如他们指出的那样,并且正如这个问题所证实的那样,在当前版本的 C# 中是不可能的:Destructuring assignment - object properties to variables in C#

最佳答案

到目前为止,我会采取与任何答案不同的方法。

static class Extensions {
public static SafeArrayReader<T> MakeSafe<T>(this T[] items)
{
return new SafeArrayReader<T>(items);
}
}
struct SafeArrayReader<T>
{
private T[] items;
public SafeArrayReader(T[] items) { this.items = items; }
public T this[int index]
{
get
{
if (items == null || index < 0 || index >= items.Length)
return default(T);
return items[index];
}
}
}

现在你有了一个数组,它给你一个默认值而不是抛出:

var remainder = GetRemainders().MakeSafe();
var input = remainder[0];
var output = remainder[1];
var config = remainder[2];

简单易行。您对数据类型的语义有疑问吗? 创建一个更好的数据类型来封装所需的语义

关于c# - 处理可变数量的输出参数,减少 C# 中的代码重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41716356/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com