How to set a property value by reflection in C#? - Tutorialspoint

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

How to set a property value by reflection in C#? - The System. Reflection namespace contains classes that allow you to obtain information ... TrendingCategories DataStructure Networking RDBMS OperatingSystem Java iOS HTML CSS Android Python CProgramming C++ C# MongoDB MySQL Javascript PHP SelectedReading UPSCIASExamsNotes Developer'sBestPractices QuestionsandAnswers EffectiveResumeWriting HRInterviewQuestions ComputerGlossary WhoisWho HowtosetapropertyvaluebyreflectioninC#? CsharpServerSideProgrammingProgramming TheSystem.Reflectionnamespacecontainsclassesthatallowyoutoobtaininformationabouttheapplicationandtodynamicallyaddtypes,values,andobjectstotheapplication.Reflectionobjectsareusedforobtainingtypeinformationatruntime.TheclassesthatgiveaccesstothemetadataofarunningprogramareintheSystem.Reflectionnamespace.Reflectionallowsviewattributeinformationatruntime.Reflectionallowsexaminingvarioustypesinanassemblyandinstantiatethesetypes.Reflectionallowslatebindingtomethodsandproperties.Reflectionallowscreatingnewtypesatruntimeandthenperformssometasksusingthosetypes.ExampleGetProperty(String)Searchesforthepublicpropertywiththespecifiedname.GetType(String,Boolean)GetstheTypeobjectwiththespecifiednameintheassemblyinstanceandoptionallythrowsanexceptionifthetypeisnotfound.SetValue(Object,Object)Setsthepropertyvalueofaspecifiedobject.classProgram{   staticvoidMain(string[]args){    Useruser=newUser();    Typetype=user.GetType();    PropertyInfoprop=type.GetProperty("Name");    prop.SetValue(user,"Bangalore",null);    System.Console.WriteLine(user.Name);    Console.ReadLine();   } } classUser{   publicintId{get;set;}   publicstringName{get;set;} }OutputBangalore NizamuddinSiddiqui Publishedon05-Nov-202013:53:15 RelatedQuestions&AnswersHowtosetapropertyhavingdifferentdatatypewithastringvalueusingreflectioninC#? ReflectioninC# HowtofetchapropertyvaluedynamicallyinC#? MirrorReflectioninC++ LineReflectioninC++ HowtodeleteanelementfromtheSetbypassingitsvalueinC++ HowtouseReflectioninGolang? SetacertainvaluefirstwithMySQLORDERBY? HowtodisplaymethodsandpropertiesusingreflectioninC#? HowtosetselecteditemofSpinnerbyvalueinsteadofbypositiononAndroid? HowtoaddareflectioneffecttoatextnodeinJavaFX? HowtopreventReflectiontobreakaSingletonClassPattern? HowdoyougiveaC#Auto-Propertyadefaultvalue? HowtosortaPythondictionarybyvalue? HowtoinstantiateastaticinnerclasswithreflectioninJava? PreviousPage PrintPage NextPage  Advertisements Print  AddNotes  Bookmarkthispage  ReportError  Suggestions Save Close Dashboard Logout



請為這篇文章評分?