我正在嘗試在運行時創建泛型對象。到目前爲止,我已經能夠創建它,但我無法弄清楚如何投射它。我所擁有的是enum對象,我想生成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
你得到的具體錯誤是什麼? –
我敢肯定這裏有重複的內容......但是您能否給我們提供更多關於您試圖用實例實現的信息,以及您是否控制了泛型? (例如,你可以創建一個非泛型基類型嗎?) –
EnumMapper <> - 什麼是類型? – progpow