将属性与 c 中的索引连接起来#

Concatenate properties with index in c#

提问人:spc 提问时间:1/30/2023 更新时间:1/30/2023 访问量:43

问:

我有一个属性为 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;  
}

但是我收到一个错误,就像预期的标识符一样。 谁能帮我解决这个问题?提前致谢。

C -3.0 C#-2.0

评论

0赞 Ryan Thomas 1/30/2023
看起来你想根据字符串设置一个属性,你需要反射来做到这一点。stackoverflow.com/questions/619767/......
2赞 shingo 1/30/2023
最好将属性定义为数组public string[] subs;
1赞 Guru Stron 1/30/2023
您真的局限于 C# 版本 2-4 吗?JIC - 最新的是 C# 11。

答:

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";
}