[英]How would I make a string get a property? C#
我得到了這個數據庫,女巫會根據我在代碼中寫的內容顯示學生的成績。 例如:
id = "Robert"
classType = "mathGrades"
這是我的代碼
public string grades;
public string loadQuery(string id, string classType)
{
students = jsonService.GetData(); // My Json reader gets data from my Json file
string Class = "student." + classType; //I combine the scripts
foreach (Student student in students)
{
if (student.name == id)//Check if we have a student by this name, if we do then get the grades for the class defined in "classType"
{
grades = string.Join(", ", Class);//This is the part that I understand why it doesn't work, but I don't have an idea on how to replace it
}
}
return grades;
}
這是學生 class:
public class Student
{
public string name { get; set; }
public List<int> mathGrades { get; set; }
public override string ToString() => JsonSerializer.Serialize(this);
}
這是包含數據的 json 文件
[
{
"name": "Test1",
"mathGrades": [ 1, 2, 3 ]
},
{
"name": "Test2",
"mathGrades": [ 1, 2, 3 ]
}
]
我希望我的 output 類似於“1、2、3”,但我只得到 student.mathGrades。 我明白為什么,我只是不知道如何解決它。 提前致謝 !
你應該改變
grades = string.Join(", ", Class);
至
grades = string.Join(", ", student.mathGrades);
上面的答案解釋了你的錯誤。 String.Join 需要值數組。 在你的例子中
string.Join(", ", "student.mathGrades");
返回student.mathGrades
您正在創建一個名為 Class 的字符串並將其設置為等於"student.mathGrades"
。
在您的循環中,您實際上是在說grades = string.Join(", ", "student.mathGrades")
由於"student.mathGrades"
只是一個字符串,所以沒有加入,它只是返回。
如果你想讓成績返回一個成績列表,你需要從某個地方提取該列表。 了解您的學生 object 的樣子會有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.