我是C#初学者。我希望你对我有耐心。可以说我有一个枚举
public enum Dogs
{
Terrier,
Poodle,
Pitbull,
}
和一些狗类
public class Terrier {
}
public class Poodle {
}
public class Pitbull {
}
而且出于某种原因,我想根据其类型(枚举值)动态实例化每个类,
foreach(Dogs d in Enum.GetValues(typeof(Dogs)))
{
// d myDog = new d();
// "...is a variable but is used like a type"
}
我也尝试过
var myDog = Activator.CreateInstance(d);
// "...cannot convert from namespace.Dogs to System.Type"
[Dogs.Terrier
与Terrier
是不同的东西。
这是您可以按照您所描述的方式进行的操作:
为简单起见,我将使所有类都实现一个公共接口IDog:
public interface IDog { }
public class Terrier : IDog
{
}
public class Poodle : IDog
{
}
public class Pitbull : IDog
{
}
现在我们可以这样做:
IDog dog;
foreach (Dogs d in Enum.GetValues(typeof(Dogs)))
{
switch (d)
{
case Dogs.Terrier:
dog = new Terrier();
break;
case Dogs.Poodle:
dog = new Poodle();
break;
case Dogs.Pitbull:
dog = new Pitbull();
break;
default:
throw new Exception("no such dog!");
}
Debug.WriteLine($"dog is {dog.GetType()}");
}