将字符串转换为变量名称以访问属性

时间:2017-08-27 14:59:12

标签: c#

我有几个名为student1 ... studentn的自定义对象。我想使用for循环来控制每个自定义对象的属性。这可能在C#中吗?我已经收集到使用字典或反射已经有效,但我无法找到与我需要的相似的情况。感谢。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            studentinfo student1 = new studentinfo("fname1", "sname1");
            studentinfo student2 = new studentinfo("fname2", "sname2");
            studentinfo student3 = new studentinfo("fname3", "sname3");

            studentinfo[] studentarray = new studentinfo[3];

            for (int i = 0; i < 3; i++)
            {
                Console.WriteLine("Student {} name: {} {}", i, studentarray[i].FirstName, studentarray[i].SurName);
            }
        }
        private class studentinfo
        {
            private string fName;
            private string sName;

            public studentinfo(string fName, string sName)
            {
                this.fName = fName;
                this.sName = sName;
            }
            public string FirstName
            {
                get { return this.fName; }
                set { if (value != null) { this.fName = value; } }
            }
            public string SurName
            {
                get { return this.sName; }
                set { if (value != null) { this.sName = value; } }
            }
        }
    }
}

0 个答案:

没有答案