从列表中获取对象名称
本文关键字:取对象 获取 列表 | 更新日期: 2023-09-27 18:04:20
是否有一种方法来检索存储在列表中的对象名称?
我想要做的是在打印出矩阵的属性之前添加一个对象名称——在这个特殊的例子中是矩阵的名称。
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());
一个写出特定对象名称的方法-矩阵
变量名作为属性
您无法检索您"曾经使用"来声明矩阵的对象引用名称。我能想到的最好的替代方案是将字符串属性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表达式获得变量名,这篇文章对此进行了解释。这里有一个小的单元测试,展示了如何在代码中应用它。
[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:注意他关于性能惩罚的警告
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());
}