c# - 从列表中获取对象名称

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

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

最佳答案

作为属性的变量名

您无法检索“曾经”用于声明矩阵的对象引用名称。我能想到的最佳替代方法是向 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:请注意他关于性能惩罚的警告。

关于c# - 从列表中获取对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15453569/

相关文章:

python - 在函数中返回列表

java - 检查字符串中的单词是否在数组中

python - 检查 Python 字典中是否存在重复的 Key 或 Value

javascript - 以不同的方法在 javascript 中添加列表

java - 使用反射创建内部类对象

c# - 如果未选择日期,如何将 datetimepicker 设置为空值 (c# winforms)

c# - 循环在构造函数中设置变量

java - 创建同一类的多个对象时出现问题

c# - Nancy 并发请求同步运行

c# - 在 WPF UserControl 上应用样式的问题