簡體   English   中英

將屬性與 c# 中的索引連接起來

[英]Concatenate properties with index in c#

我有一個 class 學生,其屬性為 sub1、sub2 和 sub3。

我想通過將屬性名稱與索引連接來使用循環訪問這些屬性以避免重復。 我試過下面的代碼

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

但是我收到了一個錯誤,就像預期的標識符一樣。 誰能幫我解決這個問題? 提前致謝。

您需要使用反射或定義索引器:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM