提问人:spc 提问时间:1/30/2023 更新时间:1/30/2023 访问量:43
将属性与 c 中的索引连接起来#
Concatenate properties with index in c#
问:
我有一个属性为 sub1、sub2 和 sub3 的班级 Student。
我想通过连接属性名称来使用循环访问这些属性 与索引一起以避免重复。我尝试了以下代码
public class SampleApplication
{
public static void Main(string[] args)
{
Student s =new Student();
for(int i=1;i<=3;i++)
{
s.$"sub{i}"="Subjects";
}
}
}
public class Student
{
public string sub1;
public string sub2;
public string sub3;
}
但是我收到一个错误,就像预期的标识符一样。 谁能帮我解决这个问题?提前致谢。
答:
1赞
Guru Stron
1/30/2023
#1
您需要使用反射或定义索引器:
public class Student
{
public string sub1;
public string sub2;
public string sub3;
public string this[int index]
{
get => index switch
{
1 => sub1,
2 => sub2,
3 => sub3,
_ => throw new ArgumentOutOfRangeException()
};
set
{
switch (index)
{
case 1:
sub1 = value;
break;
case 2:
sub2 = value;
break;
case 3:
sub3 = value;
break;
default: throw new ArgumentOutOfRangeException();
}
}
}
}
和用法:
Student s = new Student();
for (int i = 1; i <= 3; i++)
{
s[i] = "Subjects";
}
评论
public string[] subs;