Jar*_*Par 39
函数可以返回2个单独的值吗?不,C#中的函数只能返回单个值.
虽然可以使用其他概念来返回2个值.首先想到的是使用包装类型,如a Tuple<T1,T2>.
Tuple<int,string> GetValues() {
return Tuple.Create(42,"foo");
}
Run Code Online (Sandbox Code Playgroud)
该Tuple<T1,T2>类型仅适用于4.0及更高版本.如果您使用的是早期版本的框架,则可以创建自己的类型或使用KeyValuePair<TKey,TValue>.
KeyValuePair<int,string> GetValues() {
return new KeyValuePair<int,sting>(42,"foo");
}
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用out参数(我会高度推荐元组方法).
int GetValues(out string param1) {
param1 = "foo";
return 42;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*Tao 14
总之,没有.
但是你可以为此定义一个struct(或者class就此而言):
struct TwoParameters {
public double Parameter1 { get; private set; }
public double Parameter2 { get; private set; }
public TwoParameters(double param1, double param2) {
Parameter1 = param1;
Parameter2 = param2;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,这对于单个问题来说太具体了.更灵活的方法是定义一个通用的struct像Tuple<T1, T2>(如JaredPar建议的):
struct Tuple<T1, T2> {
public T1 Property1 { get; private set; }
public T2 Property2 { get; private set; }
public Tuple(T1 prop1, T2 prop2) {
Property1 = prop1;
Property2 = prop2;
}
}
Run Code Online (Sandbox Code Playgroud)
(注意,与上述非常相似的东西实际上是4.0及更高版本中.NET的一部分,显然.)
那么你可能有一些看起来像这样的方法:
public Tuple<double, int> GetPriceAndVolume() {
double price;
int volume;
// calculate price and volume
return new Tuple<double, int>(price, volume);
}
Run Code Online (Sandbox Code Playgroud)
像这样的代码:
var priceAndVolume = GetPriceAndVolume();
double price = priceAndVolume.Property1;
int volume = priceAndVolume.Property2;
Run Code Online (Sandbox Code Playgroud)
这不是直接可能的.您需要返回包含这两个参数的单个参数,或者使用out参数:
object Method(out object secondResult)
{
//...
Run Code Online (Sandbox Code Playgroud)
要么:
KeyValuePair<object,object> Method()
{
// ..
Run Code Online (Sandbox Code Playgroud)
所有可能的解决方案都遗漏了一个要点。为什么要从方法返回两个值?我认为有两种可能的情况:a)您返回的两个值实际上应该封装在一个对象中(例如,某物的高度和宽度,因此您应该返回一个表示该东西的对象)或b)这是代码的味道,您确实需要考虑一下原因该方法返回两个值(例如,该方法实际上在做两件事)。
使用C# 7,您现在可以返回ValueTuple:
static (bool success, string value) GetValue(string key)
{
if (!_dic.TryGetValue(key, out string v)) return (false, null);
return (true, v); // this is a ValueType literal
}
static void Main(string[] args)
{
var (s, v) = GetValue("foo"); // (s, v) desconstructs the returned tuple
if (s) Console.WriteLine($"foo: {v}");
}
Run Code Online (Sandbox Code Playgroud)
ValueTuple是一种值类型,与引用类型相比,这使得它成为返回值的绝佳选择Tuple- 没有对象需要被垃圾收集。
另请注意,您可以为返回的值指定名称。这真的很好。
仅出于这个原因,我希望可以声明ValueTuple只有一个元素的 a 。唉,这是不允许的:
static (string error) Foo()
{
// ... does not work: ValueTuple must contain at least two elements
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14658 次 |
| 最近记录: |