是否可以使用“新类”关键字创建类的实例? C#

问题描述 投票:1回答:1

我有一个数组,里面有我程序中某些类的名字。

string[] arr= new string[] {"company", "pokemon", "parents"}

是否可以创建这样的类的实例:

list.Add(new class( arr[0] { "sdfs", "sfds", 123} ))
c#
1个回答
1
投票

也许你正在寻找对象初始化者?

假设你有一个类Pokemon

class Pokemon {
    public string Name { get; set; }
    public string Type { get; set; }
    public int Age { get; set; }
}

和一个名为List<Pokemon>list,你可以这样做:

list.Add(new Pokemon { Name = "sdfs", Type = "sfds", Age = 123 });
© www.soinside.com 2019 - 2024. All rights reserved.