Saturday 15 May 2010

In C#, how do I initialize an Object with key/value from an Collection -


I am very lazy to type all the properties of my object, so instead:

  myObj.property1 = value1; MyObj.property2 = Value2; MyObj.property3 = Value3; MyObj.property4 = value4; MyObj.property5 = value5; ...   

Is there any way to do this?

  object myObj = new object (); Foreign currency (string quaprint in myCollection.AllKeys) {var curValue = collection [curProperty]; MyObj [curProperty] = ON; // ???????????? }    

Yes, you will need to use the system. Reflection to work:

 For  (int i = 1; i & lt; 6; i ++) {PropertyInfo prop = myObj.GetType (). GetProperty (string.Format ("property {0}", i); if (prop == null) {continue;} prop.SetValue (myObj, collection [prop.Name], null);}   

In this example, I'm assuming that there is a string indexer on the name of the property in the store (you may need to recover it in a different way). I also agree I have only 5 attributes ( i <6>), you have to set accordingly. But you get this idea.


Commented by Gimshikhel In spirit The ordering is also an option. 'I'm not working here as an example because I'm not 100% on code, but consider web services. Web Services (D) do their work with serialization.

So, you technically distribute an XML file to the object and you get all the benefits of Deserialization - and there are quite a few which I can think from the top of my head that the values ​​of propertiesA new example of the object did not > - I do not believe how it outlines - but I know that this is because I have once Followed the bug !

No comments:

Post a Comment