如何将变量用于泛型方法的类型参数

时间:2022-01-23 19:22:54

I have been working on a mini ORM, it's just a really basic converter, and I have a few enums in my application. Think of gender in this application. I have this snippet now:

我一直在研究一个迷你ORM,它只是一个非常基本的转换器,我的应用程序中有一些枚举。在这个应用程序中考虑性别。我现在有这个片段:

public T ParseEnum<T>(string value)
{
    return (T)Enum.Parse(typeof(T), value, true);
}

This works great. However, there is a catch. I need to hard-code which enum I want to have. If I want to dynamically switch to a different type, let's say Continent (an enum with 7 values), I have a problem, because I cannot know when the ORM reads which variable. Is there a solution for this?

这非常有效。然而,有一个问题。我需要硬编码我想要的枚举。如果我想动态切换到另一种类型,让我们说Continent(一个有7个值的枚举),我有一个问题,因为我不知道ORM什么时候读取哪个变量。这有解决方案吗?

A snippet of what I meant:

我的意思的片段:

ParseEnum<Continent>(reader[idx].ToString());

I want to switch out "Continent" with a variable, for example property.PropertyType.

我想用变量切换“Continent”,例如property.PropertyType。

1 个解决方案

#1


I would make ParseEnum as non generic method and then let it be typecasted wherever in the code you are ready to type cast it to a the actual enum type. Note that enumType can be an fully qualified string and then you can create System.Type from that string at run time using System.Type.GetType method.

我会将ParseEnum作为非泛型方法,然后在代码中的任何地方进行类型转换,您可以将其类型转换为实际的枚举类型。请注意,enumType可以是完全限定的字符串,然后您可以使用System.Type.GetType方法在运行时从该字符串创建System.Type。

public object ParseEnum(Type enumType, string value)
{
    return Enum.Parse(enumType, value, true);
}

#1


I would make ParseEnum as non generic method and then let it be typecasted wherever in the code you are ready to type cast it to a the actual enum type. Note that enumType can be an fully qualified string and then you can create System.Type from that string at run time using System.Type.GetType method.

我会将ParseEnum作为非泛型方法,然后在代码中的任何地方进行类型转换,您可以将其类型转换为实际的枚举类型。请注意,enumType可以是完全限定的字符串,然后您可以使用System.Type.GetType方法在运行时从该字符串创建System.Type。

public object ParseEnum(Type enumType, string value)
{
    return Enum.Parse(enumType, value, true);
}