1

リストに保存されているオブジェクトの名前を取得する方法はありますか?

私がやりたいのは、そのマトリックスのプロパティを出力する前に、オブジェクト名(この特定の場合はマトリックスの名前)を追加することです。

internal class Program
{
    private static void Main(string[] args)
    {
        //Create a collection to help iterate later
        List<Matrix> list_matrix = new List<Matrix>();

        //Test if all overloads work as they should.
        Matrix mat01 = new Matrix();
        list_matrix.Add(mat01);

        Matrix mat02 = new Matrix(3);
        list_matrix.Add(mat02);

        Matrix mat03 = new Matrix(2, 3);
        list_matrix.Add(mat03);

        Matrix mat04 = new Matrix(new[,] { { 1, 1, 3, }, { 4, 5, 6 } });
        list_matrix.Add(mat04);

        //Test if all methods work as they should.     
        foreach (Matrix mat in list_matrix) 
        {
            //Invoking counter of rows & columns
            //HERE IS what I need - instead of XXXX there should be mat01, mat02...
            Console.WriteLine("Matrix XXXX has {0} Rows and {1} Columns", mat.countRows(), mat.countColumns()); 
        }
    }
}

要するに私はここに必要です

Console.WriteLine("Matrix XXXX has {0} Rows and {1} Columns",
                  mat.countRows(),
                  mat.countColumns());

その特定のオブジェクトの名前を書き出すメソッド-マトリックス。

4

2 に答える 2

3

プロパティとしての変数名

マトリックスを宣言するために「一度使用した」オブジェクト参照名を取得することはできません。私が考えることができる最善の代替策は、文字列プロパティNameをMatrixに追加し、適切な値で設定することです。

    Matrix mat01 = new Matrix();
    mat01.Name = "mat01";
    list_matrix.Add(mat01);

    Matrix mat02 = new Matrix(3);
    mat02.Name = "mat02";
    list_matrix.Add(mat02);

そうすれば、行列の名前を出力できるようになります

foreach (Matrix mat in list_matrix)
{
    Console.WriteLine("Matrix {0} has {1} Rows and {2} Columns", 
        mat.Name, 
        mat.countRows(), 
        mat.countColumns());
}

ラムダ式を使用した代替

Bryan Crosbyが述べたように、この投稿で説明されているように、ラムダ式を使用してコードで変数名を取得する方法があります。これは、コードにどのように適用できるかを示す小さな単体テストです。

    [Test]
    public void CreateMatrix()
    {
        var matrixVariableName = new Matrix(new [,] {{1, 2, 3,}, {1, 2, 3}});
        Assert.AreEqual("matrixVariableName", GetVariableName(() => matrixVariableName));
    }

    static string GetVariableName<T>(Expression<Func<T>> expr)
    {
        var body = (MemberExpression)expr.Body;

        return body.Member.Name;
    }

PS:パフォーマンスのペナルティに関する彼の警告に注意してください。

于 2013-03-16T19:20:48.723 に答える
2
int i=0;
foreach (Matrix mat in list_matrix) 
{
 i++;
Console.WriteLine("Matrix mat{0} has {1} Rows and {2} Columns", i, mat.countRows(), mat.countColumns()); 
 }
于 2013-03-16T19:29:23.560 に答える