返回类型的C#方法
我有两个类,它们由某个ID标识(每个类都是唯一的整数)。接下来,我需要一个以整数(ID)为参数并返回相应类类型的方法。到目前为止,我已经得出以下结论:返回类型的C#方法,c#,.net,generics,return-type,C#,.net,Generics,Return Type,我有两个类,它们由某个ID标识(每个类都是唯一的整数)。接下来,我需要一个以整数(ID)为参数并返回相应类类型的方法。到目前为止,我已经得出以下结论: public static Type GetById(int id) { switch (id) { case 1: return (new ClassA()).GetType(); case 2: return (new ClassB()).GetType(); case 3: r
public static Type GetById(int id)
{
switch (id)
{
case 1: return (new ClassA()).GetType();
case 2: return (new ClassB()).GetType();
case 3: return (new ClassC()).GetType();
// ... and so on
}
}
目前看来,它是可行的,但出于某种原因,我不喜欢我必须实例化这个类来获取它的类型。这会引起什么问题吗
我发现的另一个解决方案是使用Type.GetType(classNameAsString)方法,但我想这可能会导致一些运行时错误或bug,以防类名发生更改(即,我更改了类的名称,但忘记了更新GetById方法)
有更好的方法吗?改用运算符
public static Type GetById(int id)
{
switch (id)
{
case 1: return typeof(ClassA);
case 2: return typeof(ClassB);
case 3: return typeof(ClassC);
// ... and so on
}
}
顺便说一句,我会认真质疑整个设计——将类型映射到整数感觉很奇怪。为什么不声明一个字典呢
private static Dictionary types=new Dictionary(){
{1,typeof(ClassA)},
{2,typeof(ClassB)},
{3,typeof(ClassC)},
等等
};
公共静态类型GetById(int-id){
类型结果=null;
if(type.TryGetValue(id,out结果))
返回结果;
返回null;//或引发异常
}
另一种选择是创建枚举:
public enum ClassType
{
ClassA = 1,
ClassB = 2,
ClassC = 3
}
然后更改方法以接受此enum
并返回类型:
public static Type GetById(ClassType id)
{
//Will return null if the Type is not found,
//Add true as a second parameter to throw if not found
return Type.GetType(id.ToString());
}
这样做将从代码中删除幻数,但只在类名称与枚举选项匹配时才起作用。这将使您的代码大大缩小,但正如其他人所指出的,您应该真正质疑您的应用程序设计,因为这感觉不太正确。您是否正在尝试创建工厂?不是,我只是需要类型将其提供给基础api中的泛型方法。这是否奇怪?考虑使用N值枚举来指定行为时的配置文件,并且该行为由N类提供。您需要将枚举值映射到这些类型。@Gusdor我想这并不是那么牵强。但是,这仍然会将枚举映射到类型的实例,而不是将整数映射到类型。毕竟这很奇怪!现在我觉得很尴尬,因为我的记忆力不好。。。谢谢,我会尽快接受你的答复。关于设计方面,我也不太自信,但这是在不进行重大重构的情况下完成工作的最简单方法。@Gusdor:在配置文件中,为什么不列出完整的类型名呢?这就是.NET所做的。
public static Type GetById(ClassType id)
{
//Will return null if the Type is not found,
//Add true as a second parameter to throw if not found
return Type.GetType(id.ToString());
}