我正在尝试在运行时创建一个通用对象。目前我已经成功创建了它,但是我无法弄清楚如何进行转换。我拥有枚举对象并希望生成EnumMapper,将枚举值转换为自定义字符串以映射到遗留数据库。
Type enumType = myEnum.GetType();
Type enumMapperType = typeof(EnumMapper<>)
.GetGenericTypeDefinition().MakeGenericType(enumType);
var mapper = Activator.CreateInstance(enumMapperType); // OK
EnumMapper<> mapper = (EnumMapper<>) Activator.CreateInstance(enumMapperType); // Error
当我在调试器中检查对象时,它被创建成我所期望的那样,但是如何转换它以便我可以使用它?
这个类:
public class EnumMapper<T> : IEnumMapper<T>
接口:
public interface IEnumMapper<T>
{
T EnumValue(string value);
bool HasEnumValue(string stringValue);
bool HasStringValue(T enumValue);
string StringValue(T enumValue);
}
Error 2 ; expected \EnumMapperTest.cs 36
Error 4 ; expected \EnumMapperTest.cs 36
Error 1 Invalid expression term '>' \EnumMapperTest.cs 36
Error 3 Invalid expression term '>' \EnumMapperTest.cs 36
Error 34 Only assignment, call, increment, decrement, and new object expressions can be used as a statement \EnumMapperTest.cs 36
Error 36 The name 'mapper' does not exist in the current context \EnumMapperTest.cs 36
Error 35 Using the generic type 'EnumMapper<T>' requires 1 type arguments \EnumMapperTest.cs 36
Error 37 Using the generic type 'EnumMapper<T>' requires 1 type arguments \EnumMapperTest.cs 36