[英]C# Getting Type out of a string variable and using it in generic method
我希望能夠以某種方式(即從數據庫)獲取我收到的字符串值的實際類型,因此我可以在通用方法(如DoSomething<Type>()
使用該類型。
在我的項目中,我在MyCompany.MySolution.Vehicle
命名空間中有Plane
和Car
類,就像這樣
- MyCompany.MySolution.Vehicle
|+Interfaces
|-Implementations
|-Car
|-Plane
我以字符串形式接收車輛的類型。 因此,我得到字符串“ Car”,這意味着,我需要獲得Type Car
以便可以在通用方法中使用該類型來注冊它,如下所示:
MyFactory.Register<Car>(carId)
因此,MyFactory是調用Register()方法的靜態類。
同樣,我收到字符串“ Plane”,這意味着,我需要獲取Type Plane
以便可以在上面的通用方法中使用該類型來注冊Plane。
我嘗試使用類似
MyFactory.Register<Type.GetType("MyCompany.MySolution.Vehicle.Implementations.Car")>(carId)
,但這不起作用。
如果要使用運行時生成的Type參數調用泛型方法,則可以執行以下操作:
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);
請注意:
這不是應該使用泛型的方式。 我只是指出可能性,而不是為您提出的問題提供理想的答案。 也許您應該重新考慮一些建築設計選擇!
如果Register<T>
做這樣的事情
void Register<T>(int id)
{
_dictionary.Add(typeof(T), ...);
}
創建非通用重載
void Register(Type t, int id)
{
_dictionary.Add(t, ...);
}
這種新的重載不是類型安全的,但是無論如何都不能從字符串中創建類型。
泛型的目的是在保持類型安全的同時獲得可變性(不要與動態行為混淆!)。 但是,當在運行時確定類型時,就沒有給出類型安全性,泛型更多的是障礙,而不是有用的。
請注意,編譯器可確保類型安全,這當然在運行時不起作用。
您可以使用包含所有具有字符串鍵的類型的字典:
var d = new Dictionary<String,Type>();
d.Add("Car",typeof(Car));
d.Add("Plane",typeof(Plane));
然后,如果您從數據庫中獲得字符串“ Car”,則可以得到如下類型:
var myType = d["Car"];
然后使用myType
作為真實類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.