GetOriginalTypeParameterType throws Object reference not set to an instance of an object exception

后端 未结 1 1376
一整个雨季
一整个雨季 2021-01-18 04:33

Reference: How can a dynamic be used as a generic?

public void CheckEntity(int entityId, string entityType = null)
{
 dynamic AnyObject = Activator.CreateIns         


        
相关标签:
1条回答
  • 2021-01-18 05:02

    As discussed in C# chat room, the solution here is to bypass dynamic entirely and use reflection to invoke the generic method. Dynamic has some nice features but sometimes causes more trouble than it's worth, especially when it's possible to get the Type object at runtime.

    var modelType = Type.GetType("InferenceExample.Models." + entityType + ",InferenceExample");
    
    var checkMethod = typeof(HomeController).GetMethod("CheckWithInference", BindingFlags.NonPublic | BindingFlags.Static);
    checkMethod.MakeGenericMethod(modelType).Invoke(null, new object[] { entityId });
    

    Glad to help :)

    0 讨论(0)
提交回复
热议问题