C# Getting Type out of a string variable and using it in generic method

前端 未结 3 1485
灰色年华
灰色年华 2021-01-29 05:59

I want to be able to get the actual Type of a string value I receive by some means (i.e from database) so I can use that Type in generic method like DoSomething

3条回答
  •  不要未来只要你来
    2021-01-29 06:28

    If you want to invoke a Generic Method with a Type parameter generate at Runtime, you could do something like this:

    var vehicleString = "Car";
    
    // use the fully-qualified name of the type here
    // (assuming Car is in the same assembly as this code, 
    //  if not add a ", TargetAssemblyName" to the end of the string)
    var vehicleType = 
        Type.GetType($"MyCompany.MySolution.Vehicle.Implementations.{vehicleString}");
    
    // assuming MyFactory is the name of the class 
    // containing the Register-Method
    typeof(MyFactory).GetMethod("Register")
        .MakeGenericMethod(vehicleType)
        .Invoke(this);
    

    Working Example

    Just as a note:

    This is not how generics are supposed to be used. I'm just pointing out the possibility, not giving you an ideal answer to the problem you're proposing. Maybe you should rethink some of your architectural design choices!

提交回复
热议问题