2011-12-15 12 views
11

は私がC#でタプルとアンパックアサインをサポートしていますか? Pythonで

def myMethod(): 
    #some work to find the row and col 
    return (row, col) 

row, col = myMethod() 
mylist[row][col] # do work on this element 

を書くことができます。しかし、C#で、私は自分自身がPython的な方法は、obivously非常にきれいです

int[] MyMethod() 
{ 
    // some work to find row and col 
    return new int[] { row, col } 
} 

int[] coords = MyMethod(); 
mylist[coords[0]][coords[1]] //do work on this element 

を書き出す見つけます。 C#でこれを行う方法はありますか?

+1

私はたぶんそのためのパラメータを使用しています。 –

+1

@MikeChristensen:フレームワーク設計ガイドラインでは、避けることができる場合はパラメータに対して推奨しています。 – dtb

+1

@MikeChristensen私はパラメータについて考えましたが、何らかの理由で汚い気分にさせてしまいます。 –

答えて

14

.NETでTupleクラスのセットがあります:

Tuple<int, int> MyMethod() 
{ 
    // some work to find row and col 
    return Tuple.Create(row, col); 
} 

は、しかし、Pythonでのようにそれらを開梱ためのコンパクトな構文はありません。

Tuple<int, int> coords = MyMethod(); 
mylist[coords.Item1][coords.Item2] //do work on this element 
+2

因果律読者のための注意: 'Tuple <...>'は.NET4 +の標準です。 –

+0

他の読者の場合は、代わりにKeyValuePairを使用して、2タプルを.NET <4(本質的に)で作成することができます。 – fabspro

1

C#がタイプと強く型付けされた言語でありますシステムは、関数がnone(void)または1つの戻り値のいずれかを持つことができるという規則を適用します。 C#4.0は、タプルクラス紹介:

Tuple<int, int> MyMethod() 
{ 
    return Tuple.Create(0, 1); 
} 

// Usage: 
var myTuple = MyMethod(); 
var row = myTuple.Item1; // value of 0 
var col = myTuple.Item2; // value of 1 
+13

強く型付けされた言語は、単一の値を返すことに限定されません。スキームの一例です。強いタイピング!=静的なタイピング; PythonとSchemeは強く動的に型指定されています。 –

+2

これは事実ですが、C#の型システムは関数の戻り値を単一の型に限定すると言われるべきでしょう。 –

+0

実際、それは本当です:) –

6

拡張子が近いPythonのタプルアンパックにそれを得るかもしれないが、ないより効率的なが、より読みやすい(とPython的):

public class Extensions 
{ 
    public static void UnpackTo<T1, T2>(this Tuple<T1, T2> t, out T1 v1, out T2 v2) 
    { 
    v1 = t.Item1; 
    v2 = t.Item2; 
    } 
} 

Tuple<int, int> MyMethod() 
{ 
    // some work to find row and col 
    return Tuple.Create(row, col); 
} 

int row, col;  
MyMethod().UnpackTo(out row, out col); 
mylist[row][col]; // do work on this element 
8

ので、C#7は、使用することができますValueTuple

Install-Package System.ValueTuple 

次にあなたがValueTuplesをパックし、アンパックすることができます

(int, int) MyMethod() 
{ 
    return (row, col); 
} 

(int row, int col) = MyMethod(); 
// mylist[row][col] 
関連する問題