Public Static ObjectChangeType (Objectvalue, Type targetType) { if(Targettype.isgenerictype && targettype.getgenerictypedefinition () = =typeof(nullable<>) {nullableconverter Nullableconverter=NewNullableconverter (TargetType); Type Converttype=Nullableconverter.underlyingtype; returnConvert.changetype (value, Converttype); } if(Value = =NULL&&targettype.isgenerictype) {returnActivator.CreateInstance (TargetType); } if(Value = =NULL) { return NULL; } if(TargetType = =value. GetType ()) {returnvalue; } if(targettype.isenum) {if(Value is string) { returnEnum.parse (TargetType, value as string); } Else { returnenum.toobject (TargetType, value); } } if(!targettype.isinterface &&targettype.isgenerictype) {Type Innertype= Targettype.getgenericarguments () [0]; ObjectInnervalue =changetype (value, Innertype); returnActivator.CreateInstance (TargetType,New Object[] {innervalue}); } if(Value is string&& TargetType = =typeof(Guid)) { return NewGuid (value as string); } if(Value is string&& TargetType = =typeof(Version)) { return NewVersion (value as string); } if(! (Value isiconvertible)) { returnvalue; } returnConvert.changetype (value, TargetType); }
A handy C # type converter