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

How to use a variable for the type parameter of a generic method

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

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

效果很好。但是,有一个陷阱。我需要硬编码我想要的枚举。如果我想动态切换到不同的类型,比如说大陆(一个有 7 个值的枚举),我就有问题了,因为我不知道 ORM 何时读取哪个变量。有解决办法吗?

我的意思的一个片段:

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

我想用变量切换出 "Continent",例如 property.PropertyType。

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

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