将字符串转换为T
我有一个方法需要将字符串转换为generics类型:
T GetValue(string name) { string item = getstuff(name); return item converted to T // ???????? }
T可以是int或date。
你可以使用Convert.ChangeType
T GetValue(string name) { string item = getstuff(name); return (T)Convert.ChangeType(item, typeof(T)); }
如果您只需要为int和DateTime限制输入类型,请添加如下所示的条件
if (typeof(T) != typeof(int) && typeof(T) != typeof(DateTime)) { // do something with other types }