0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

c# メンバ変数に一括 代入

Posted at
Base.cs
class Document
{
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Name3 { get; set; }
    public string Name4 { get; set; }
    public string Name5 { get; set; }
 
    public int Age1 { get; set; }
    public int Age2 { get; set; }
    public int Age3 { get; set; }
    public int Age4 { get; set; }
    public int Age5 { get; set; }
}
 
class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}
InsertToDocument.cs
List&<Person> people = new List<Person>gt;
{
    new Person { Name = "Taro", Age = 31 },
    new Person { Name = "Hanako", Age = 33 },
    new Person { Name = "Hitoshi", Age = 17 },
    new Person { Name = "Yoshie", Age = 28 },
    new Person { Name = "Kenta", Age = 21 }
};
Reflection.cs
Document doc1 = new Document();
int index = 1;
foreach (var item in people)
{
    // Name[1-5]プロパティに動的にアクセスし、値を設定
    var nameProperty = typeof(Document).GetProperty("Name" + index.ToString());
    nameProperty.SetValue(doc1, item.Name);
 
    // Age[1-5]プロパティに動的にアクセスし、値を設定
    var ageProperty = typeof(Document).GetProperty("Age" + index.ToString());
    ageProperty.SetValue(doc1, item.Age);
 
    index++;
}
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?