使用一个枚举来选择哪一个类实例 [英] Use an enum to select which class to instantiate
问题描述
我有我试图关联到DTO的一个枚举:
I have an enum that I am trying to associate to dto's:
public enum DtoSelection
{
dto1,
dto2,
dto3,
}
有在此枚举108和值
我为每个DTO的一个DTO对象:
I have a dto object for each of these dto's:
public class dto1 : AbstractDto
{
public int Id { get; set; }
//some stuff specific to this dto
}
我想使一个方法(最终服务),将返回箱中的问题关联到所述DTO的类型的新DTO对象
I am trying to make a method (eventually a service) that will return me a new dto object of the type associated to the the dto in question:
private AbstractDto(int id)
{
if (id == DtoSelection.Dto1.ToInt()) //extension method I wrote for enums
return new Dto1();
if (id == DtoSelection.Dto2.ToInt())
return new Dto2();
}
显然,我不希望这样做108次。无论出于何种原因,我的大脑只是缺少明显的东西。什么是处理这个问题的最好办法。
Obviously I do not want to do this 108 times. For whatever reason my brain is just missing something obvious. What is the best way to handle this.
推荐答案
这个类会做的DTO类在同一个命名空间AbstractDto定义你想,只要什么(你会需要调整它,如果没有):
This class will do what you want as long as the Dto classes are defined in the same namespace as AbstractDto (you'll need to tweak it if not):
由于以下枚举和类:
public enum DtoSelection
{
Dto1,
Dto2,
Dto3,
}
public abstract class AbstractDto
{
}
public class Dto1 : AbstractDto
{
}
public class Dto2 : AbstractDto
{
}
public class Dto3 : AbstractDto
{
}
这方法解决这些问题:
public static class DtoFactory
{
public static AbstractDto Create(DtoSelection dtoSelection)
{
var type = Type.GetType(typeof(AbstractDto).Namespace + "." + dtoSelection.ToString(), throwOnError: false);
if (type == null)
{
throw new InvalidOperationException(dtoSelection.ToString() + " is not a known dto type");
}
if (!typeof(AbstractDto).IsAssignableFrom(type))
{
throw new InvalidOperationException(type.Name + " does not inherit from AbstractDto");
}
return (AbstractDto)Activator.CreateInstance(type);
}
}
这篇关于使用一个枚举来选择哪一个类实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!