|
public static T GetMyDate<T>(object val,string format="yyyy-MM-dd") { T cobj; Type ctype = typeof(T); try { //cobj = (T)Activator.CreateInstance(ctype);//动态实力化反射回来的指定空间下的指定类 //cobj = (T)val; if(ctype.Name.toLower().equals("datetime")) { cobj = (T)(object)DateTime.ParseExact(val,format,null); }else { cobj = (T)Convert.ChangeType(val,ctype); } } catch { try { cobj = default(T); } catch { throw; } } return cobj; } 调用:int num = GetMyDate<int>("1"); DateTime tim = GetMyDate<DateTime>("2011-04-07","yyyy-MM-dd"); |