简体   繁体   English

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

[英]Concatenate properties with index in c#

I have a class Student with properties sub1,sub2, and sub3.我有一个 class 学生,其属性为 sub1、sub2 和 sub3。

I want to access those properties using a loop by concatenating the property name with an index in order to avoid duplication.我想通过将属性名称与索引连接来使用循环访问这些属性以避免重复。 I tried below code我试过下面的代码

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

But I am getting an error like the identifier expected.但是我收到了一个错误,就像预期的标识符一样。 Can anyone help me to solve this?谁能帮我解决这个问题? Thanks in advance.提前致谢。

You need either use reflection or define an indexer:您需要使用反射或定义索引器:

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();
            }
        }
    }
}

And usage:和用法:

Student s = new Student();
for (int i = 1; i <= 3; i++)
{
     s[i] = "Subjects";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM