Setting a property by reflection with a string value - Stack ...

文章推薦指數: 80 %
投票人數:10人

I'd like to set a property of an object through Reflection, with a value of type string . So, for instance, suppose I have a Ship class, ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore Settingapropertybyreflectionwithastringvalue AskQuestion Asked 12years,8monthsago Modified 2years,6monthsago Viewed 311ktimes 341 82 I'dliketosetapropertyofanobjectthroughReflection,withavalueoftypestring. So,forinstance,supposeIhaveaShipclass,withapropertyofLatitude,whichisadouble. Here'swhatI'dliketodo: Shipship=newShip(); stringvalue="5.5"; PropertyInfopropertyInfo=ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship,value,null); Asis,thisthrowsanArgumentException: Objectoftype'System.String'cannotbeconvertedtotype'System.Double'. HowcanIconvertvaluetothepropertype,basedonpropertyInfo? c#reflectiontype-conversionpropertyinfosetvalue Share Follow editedAug6,2015at8:46 Irshad 2,93355goldbadges2727silverbadges4747bronzebadges askedJul6,2009at20:43 DavidHodgsonDavidHodgson 9,7741717goldbadges5454silverbadges7777bronzebadges 1 1 Questionforyou:isthispartofacustomORMsolution? – user3308043 Jun5,2014at21:19 Addacomment  |  12Answers 12 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 571 YoucanuseConvert.ChangeType()-ItallowsyoutouseruntimeinformationonanyIConvertibletypetochangerepresentationformats.Notallconversionsarepossible,though,andyoumayneedtowritespecialcaselogicifyouwanttosupportconversionsfromtypesthatarenotIConvertible. Thecorrespondingcode(withoutexceptionhandlingorspecialcaselogic)wouldbe: Shipship=newShip(); stringvalue="5.5"; PropertyInfopropertyInfo=ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship,Convert.ChangeType(value,propertyInfo.PropertyType),null); Share Follow editedAug6,2015at8:31 Irshad 2,93355goldbadges2727silverbadges4747bronzebadges answeredJul6,2009at20:44 LBushkinLBushkin 125k3131goldbadges211211silverbadges261261bronzebadges 2 Review@AliKaracaanswerbelow.Boththisandtheonebelowarefastandloosebutdothejobforcommontypes. – AaronHudon Feb18,2019at7:21 IsthereaTryChangeTypeorCanChangeType? – ShimmyWeitzhandler Aug7,2019at4:37 Addacomment  |  35 Asseveralothershavesaid,youwanttouseConvert.ChangeType: propertyInfo.SetValue(ship, Convert.ChangeType(value,propertyInfo.PropertyType), null); Infact,IrecommendyoulookattheentireConvertClass. Thisclass,andmanyotherusefulclassesarepartoftheSystemNamespace.IfinditusefultoscanthatnamespaceeveryyearorsotoseewhatfeaturesI'vemissed.Giveitatry! Share Follow editedAug6,2015at8:57 Irshad 2,93355goldbadges2727silverbadges4747bronzebadges answeredJul6,2009at20:44 JohnSaundersJohnSaunders 159k2525goldbadges236236silverbadges392392bronzebadges 2 1 TheOPprobablywantsthegeneralanswer,forsettingapropertyofanytypethathasanobviousconversionfromastring. – DanielEarwicker Jul6,2009at20:48 Goodpoint.I'lleditandpointtotherealanswerers,orwilldeletemineifsomeonewilladdwhatIsaidabouttherestofthenamespace. – JohnSaunders Jul6,2009at20:50 Addacomment  |  22 ItriedtheanswerfromLBushkinanditworkedgreat,butitwon'tworkfornullvaluesandnullablefields.SoI'vechangedittothis: propertyName="Latitude"; PropertyInfopropertyInfo=ship.GetType().GetProperty(propertyName); if(propertyInfo!=null) { Typet=Nullable.GetUnderlyingType(propertyInfo.PropertyType)??propertyInfo.PropertyType; objectsafeValue=(value==null)?null:Convert.ChangeType(value,t); propertyInfo.SetValue(ship,safeValue,null); } Share Follow answeredJan4,2017at14:51 AshkanSAshkanS 8,55055goldbadges4545silverbadges7171bronzebadges 1 IhavetosaythankyouasImetthiscaseandthisistheonlyonesolution.thanks~! – Franva Apr26,2019at15:40 Addacomment  |  20 InoticealotofpeoplearerecommendingConvert.ChangeType-ThisdoesworkforsomecaseshoweverassoonasyoustartinvolvingnullabletypesyouwillstartreceivingInvalidCastExceptions: http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx Awrapperwaswrittenafewyearsagotohandlethisbutthatisn'tperfecteither. http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx Share Follow editedAug6,2015at9:09 Irshad 2,93355goldbadges2727silverbadges4747bronzebadges answeredAug13,2010at11:08 TabletTablet 4,02899goldbadges3333silverbadges5151bronzebadges Addacomment  |  12 Youcanuseatypeconverter(noerrorchecking): Shipship=newShip(); stringvalue="5.5"; varproperty=ship.GetType().GetProperty("Latitude"); varconvertedValue=property.Converter.ConvertFrom(value); property.SetValue(self,convertedValue); Intermsoforganizingthecode,youcouldcreateakind-ofmixinthatwouldresultincodelikethis: Shipship=newShip(); ship.SetPropertyAsString("Latitude","5.5"); Thiswouldbeachievedwiththiscode: publicinterfaceMPropertyAsStringSettable{} publicstaticclassPropertyAsStringSettable{ publicstaticvoidSetPropertyAsString( thisMPropertyAsStringSettableself,stringpropertyName,stringvalue){ varproperty=TypeDescriptor.GetProperties(self)[propertyName]; varconvertedValue=property.Converter.ConvertFrom(value); property.SetValue(self,convertedValue); } } publicclassShip:MPropertyAsStringSettable{ publicdoubleLatitude{get;set;} //... } MPropertyAsStringSettablecanbereusedformanydifferentclasses. Youcanalsocreateyourowncustomtypeconverterstoattachtoyourpropertiesorclasses: publicclassShip:MPropertyAsStringSettable{ publicLatitudeLatitude{get;set;} //... } [TypeConverter(typeof(LatitudeConverter))] publicclassLatitude{...} Share Follow editedDec15,2015at10:48 answeredSep13,2010at13:51 JordãoJordão 53k1212goldbadges110110silverbadges140140bronzebadges 2 Isthereanyparticularreasonwhyyouaddedthemarkerinsterfaceinsteadofjustusingobject? – Groo Dec15,2015at8:44 1 Yes,themarkerinterfaceservesasaplaceholdertoaddtheextensionmethodsto.Usingobjectwouldaddtheextensionmethodstoallclasses,whichisnotgenerallydesirable. – Jordão Dec15,2015at10:36 Addacomment  |  6 You'reprobablylookingfortheConvert.ChangeTypemethod.Forexample: Shipship=newShip(); stringvalue="5.5"; PropertyInfopropertyInfo=ship.GetType().GetProperty("Latitude"); propertyInfo.SetValue(ship,Convert.ChangeType(value,propertyInfo.PropertyType),null); Share Follow answeredJul6,2009at20:48 JohnCalsbeekJohnCalsbeek 34.9k77goldbadges9191silverbadges100100bronzebadges Addacomment  |  5 UsingConvert.ChangeTypeandgettingthetypetoconvertfromthePropertyInfo.PropertyType. propertyInfo.SetValue(ship, Convert.ChangeType(value,propertyInfo.PropertyType), null); Share Follow editedAug6,2015at8:47 Irshad 2,93355goldbadges2727silverbadges4747bronzebadges answeredJul6,2009at20:48 tvanfossontvanfosson 506k9797goldbadges692692silverbadges791791bronzebadges Addacomment  |  5 Iwillanswerthiswithageneralanswer.Usuallytheseanswersnotworkingwithguids.Hereisaworkingversionwithguidstoo. varstringVal="6e3ba183-89d9-e611-80c2-00155dcfb231";//guidvalueasstringtoset varprop=obj.GetType().GetProperty("FooGuidProperty");//propertytobesetted varpropType=prop.PropertyType; //varwillbetypeofguidhere varvalWithRealType=TypeDescriptor.GetConverter(propType).ConvertFrom(stringVal); Share Follow answeredMay30,2018at8:35 AliKaracaAliKaraca 2,5853030silverbadges3535bronzebadges 2 1 Thisshouldbetheacceptedanswer.ItalsoworkswithGUIDs<3.Thanks,Ali(that'smydaughter'snickname) – CătălinRădoi Sep13,2018at13:53 Butstillseemsnottoworkwithnullabletypes. – Auspex Apr27,2021at15:17 Addacomment  |  3 Oryoucouldtry: propertyInfo.SetValue(ship,Convert.ChangeType(value,propertyInfo.PropertyType),null); //ButthiswillcauseproblemsifyourstringvalueIsNullOrEmplty... Share Follow answeredJul6,2009at20:47 bytebenderbytebender 7,19622goldbadges2828silverbadges5454bronzebadges Addacomment  |  2 IfyouarewritingMetroapp,youshoulduseothercode: Shipship=newShip(); stringvalue="5.5"; PropertyInfopropertyInfo=ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude"); propertyInfo.SetValue(ship,Convert.ChangeType(value,propertyInfo.PropertyType)); Note: ship.GetType().GetTypeInfo().GetDeclaredProperty("Latitude"); insteadof ship.GetType().GetProperty("Latitude"); Share Follow answeredOct10,2013at8:22 SerhiySerhiy 32355silverbadges1212bronzebadges Addacomment  |  0 Usingthefollowingcodeshouldsolveyourissue: item.SetProperty(prop.Name,Convert.ChangeType(item.GetProperty(prop.Name).ToString().Trim(),prop.PropertyType)); Share Follow editedJun3,2019at10:37 Karl 84588silverbadges2121bronzebadges answeredJun3,2019at10:16 MarcoSottoMarcoSotto 1 Addacomment  |  -11 AreyoulookingtoplayaroundwithReflectionorareyoulookingtobuildaproductionpieceofsoftware?Iwouldquestionwhyyou'reusingreflectiontosetaproperty. Doublenew_latitude; Double.TryParse(value,outnew_latitude); ship.Latitude=new_latitude; Share Follow answeredJul6,2009at20:57 clemahieuclemahieu 1,43999silverbadges99bronzebadges 2 1 Youshouldrespectwhatpeopleattempttodoandnotwhatyouthinktheymustdo.Downvoted.(FromGenericProgramming.exe:ReflectionBenefits()) – ПетърПетров Sep30,2016at14:33 Er,perhapsbecauseyoudon'tknowwhatthePropertyisbeforehand,andwhileit'stypedthevalueyou'reusingisalwaysastring?Thisismycase:I'mscreenscrapingHTML,sothevalueIgetisalwaysastring,andwhichpropertiesIwantandhowtofindthemaredefinedinaconfigfile,soReflectionistheonlyreasonablewaytodoit. – Auspex Apr27,2021at15:10 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc#reflectiontype-conversionpropertyinfosetvalueoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems GettingthroughaSOC2auditwithyournervesintact FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 48 C#dynamicallysetproperty -1 LocatingClassPropertybyNamefromanString -1 Changepropertyvalue 92 Setting/gettingtheclasspropertiesbystringname 29 C#creatinginstanceofclassandsetpropertiesbynameinstring 22 HowtosetVauestotheNestedPropertyusingC#Reflection.? 10 HowtoCopyDataFromSqlObjecttoC#ModelProperty 5 Howtoassignastringtoanintegerfieldviareflection 3 dynamicallyworkwithdifferentclasses 2 .netcoreC#usedynamicpropertynameonEFCoreDatabasefirstgeneratedmodelclass Seemorelinkedquestions Related 7159 WhatisthedifferencebetweenStringandstringinC#? 2405 Whatisreflectionandwhyisituseful? 2184 WhatisthebestwaytogiveaC#auto-propertyaninitialvalue? 1210 HowdoIusereflectiontocallagenericmethod? 2588 HowdoIparseastringtoafloatorint? 3229 Caseinsensitive'Contains(string)' 529 HowtouseLINQtoselectobjectwithminimumormaximumpropertyvalue 1085 Getpropertyvaluefromstringusingreflection 3344 HowdoIconvertaStringtoanintinJava? HotNetworkQuestions findduplicate1stcolumnandconcatitsvaluesinsingleline WhydoesahypersonicmissileneedtocruiseEarthatlowaltitudebeforehittingitsmark? ITstaffsaidthatLinuxcannotconnecttotheschool'sInternet(EduStar)andrefusedtotry WhatwastheethniccompositionofSovietgovernment? Depassivavocecumverbisquaecasumdativumpostulant Howcanfourbethehalfoffive? InterpretationofasubtoureliminationconstraintintheTSP IsitappropriatetocoldcallaprospectivepostdocPI? Inacyberpunkworldwherecorporateupperclasscitizenscanworkvirtuallythroughimplants,whywouldtheybuildcorporatemega-skyscrapers? Plantingmulberrytoodeep Whataresomegoodoptionsformuseums/memorialstolearnmoreaboutthehistoryofJimCrow/lynching IsitoktohaveaPCBtrackcrossanotheronadifferentlayer? HowcanIfindhotelsinagivenareathatrentunitswithaseparatebedroom? Howtogetamotorcycletoaskillstest HowcanIrotatea2Dshapewithrespecttoanother? Whenandhowtoleaveafacultypositionforanewdepartment/universityorindustry Simplequadraticfunction,butcan'tunderstandthequestion HowDoesBlackWinThisposition Whatisthenextmoveonthisminesweeperboard? IfIdisagreewiththeresearchcommunity,shouldIreviewpapersaccordingtomybeliefsorthecommunity's? Isitimpolitetosendtheprofessorapre-writtenletterofrecommendationforapproval? TikZarcwithextremeangle Separatingbusinesslogicfromdatatemptsmetouseinstanceof Spaceshipshooter morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?