C#从字符串变量中获取类型并在泛型方法中使用它

C#从字符串变量中获取类型并在泛型方法中使用它

问题描述:

我希望能够通过某种方式(即从数据库)获取我接收到的字符串值的实际类型,因此我可以在诸如DoSomething<Type>()之类的通用方法中使用该类型.

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<Type>().

在我的项目中,我在MyCompany.MySolution.Vehicle命名空间中有类PlaneCar这样

In my project, I have classes Plane, and Car located in MyCompany.MySolution.Vehicle namespace like so

- MyCompany.MySolution.Vehicle
  |+Interfaces
  |-Implementations
    |-Car
    |-Plane

我以字符串形式接收车辆的类型.因此,我得到字符串"Car",这意味着我需要获取Type Car,以便可以在通用方法中使用该类型进行注册,如下所示:

I receive type of the vehicle as a string. So, I get string "Car" which means, I need to get Type Car so I can use that type in a generic method to register it like so:

MyFactory.Register<Car>(carId)

因此,MyFactory是调用Register()方法的静态类.

So, MyFactory is static class calling Register() method.

类似地,我收到字符串"Plane",这意味着我需要获取Type Plane,以便可以在上面的通用方法中使用该类型来注册Plane.

Similarly, I receive string "Plane" which means, I need to get Type Plane so I can use that type in the generic method above to register a Plane.

我尝试使用类似的东西

MyFactory.Register<Type.GetType("MyCompany.MySolution.Vehicle.Implementations.Car")>(carId)

,但这不起作用.

如果要使用在运行时生成的Type参数调用泛型方法,您可以可以执行以下操作:

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<T>-Method
typeof(MyFactory).GetMethod("Register")
    .MakeGenericMethod(vehicleType)
    .Invoke(this);

工作示例

请注意:

不是 这是应该使用泛型的方式.我只是指出可能性,而不是为您提出的问题提供理想的答案.也许您应该重新考虑一些建筑设计选择!

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!