如何在 C# 中正确访问对象的 List<> 值?

  • 本文关键字:List 对象 访问 c#
  • 更新时间 :
  • 英文 :


我试图获得对象值,但我不知道如何做到这一点。我是c#的新手,它给了我语法错误。我想通过PrintSample&quot方法单独打印它如何连接或追加whatData变量。谢谢你。

PrintSample(getData, "name");
PrintSample(getData, "phone");
PrintSample(getData, "address");

//Reading the CSV file and put it in the object
string[] lines = File.ReadAllLines("sampleData.csv");
var list = new List<Sample>();
foreach (var line in lines)
{
var values = line.Split(',');
var sampleData = new Sample()
{
name = values[0],
phone = values[1],
address = values[2]
};
list.Add(sampleData);
}
public class Sample
{
public string name { get; set; }
public string phone { get; set; }
public string adress { get; set; }
}
//Method to call to print the Data
private static void PrintSample(Sample getData, string whatData)
{
//THis is where I'm having error, how can I just append the whatData to the x.?
Console.WriteLine( $"{getData. + whatData}"); 

}

在c#中不可能动态求值像

这样的表达式
$"{getData. + whatData}"

与JavaScript等语言相反。

我建议使用切换表达式或Dictionary<string, string>

public void PrintData(Sample sample, string whatData)
{
var data = whatData switch
{
"name" => sample.name,
"phone" => sample.phone,
"address" => sample.address
_ => throw new ArgumentOutOfRangeException(nameof(whatData)),
};
Console.WriteLine(data);
}

我不知道你想达到什么目的。也许这对你有帮助:

private static void PrintSample(Sample getData, string whatData)
{
var property = getData.GetType().GetProperty(whatData);
string value = (string)property?.GetValue(getData) ?? "";
Console.WriteLine($"{value}");
}

PO真正需要的是

private static void PrintSamples(List<Sample> samples)
{
foreach (var sample in samples)
Console.WriteLine($"name : {sample.name} phone: {sample.phone} address: {sample.address} ");
}

和代码

var list = new List<Sample>();
foreach (var line in lines)
{
......
}
PrintSamples(list);

使用

是激进的
PrintSample(getData, "name");

而不是

PrintSample(getData.name)

您可以使用反射来做到这一点。然而,众所周知,它是相对较慢的。

public static void PrintSample(object getData, string whatData)
{
Console.WriteLine( $"{getData.GetType().GetProperty(whatData).GetValue(getData, null)}");
}

相关内容

最新更新