usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Reflection;usingSystem.Data;namespaceconsoleapplication11{classProgram {Static voidMain (string[] args) { varDT =NewDataTable (); Dt. Columns.Add ("C1",typeof(string)); varrow =dt. NewRow (); row["C1"] ="ABC"; varc = getdatafromdbfield<Double> (row["C1"],2);//returns 2 varD = getdatafromdbfield<Object> (row["C1"],2);//return to "ABC" } Private StaticT getdatafromdbfield<t> (Objectobj, T defaultvalue =default(T)) {if(obj = =NULL|| obj = =DBNull.Value)returnDefaultValue; Type T=typeof(T); varTryParse = T.getmethod ("TryParse", BindingFlags.Public |bindingflags.static, Type.defaultbinder,Newtype[] {obj. GetType (), T.makebyreftype ()},NewParametermodifier[] {NewParameterModifier (2) }); if(TryParse! =NULL) { varParameters =New Object[] {obj, activator.createinstance (t)}; BOOLSuccess = (BOOL) Tryparse.invoke (NULL, parameters); if(Success)return(T) parameters[1]; Else returnDefaultValue; } returnT Convert.changetype (obj,typeof(T)); } }}
C # generic TryParse type conversions