从列表中获取对象名称

时间:2013-03-16 19:16:37

标签: c# list object identifier

有没有办法检索存储在列表中的对象的名称?

我想要做的是在打印出该矩阵的属性之前添加一个对象名称 - 在这种特殊情况下的矩阵名称。

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());

写出特定对象名称的方法 - 矩阵。

2 个答案:

答案 0 :(得分:3)

变量名称为属性

您无法检索“曾经使用过”的对象引用名称来声明矩阵。我能想到的最好的替代方法是向Matrix添加字符串属性Name并使用适当的值设置它。

    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());
}

使用Lambda表达式

的备选方案

正如Bryan Crosby所提到的,有一种方法可以使用lambda表达式explained in this post在代码中获取变量名。这是一个小型的单元测试,展示了如何在代码中应用它。

    [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:请注意他对性能处罚的警告。

答案 1 :(得分: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()); 
 }