0

I have a queue containing a bunch of class objects. If possible, I'd like to get them all and instantiate them as new objects dynamically.

Of course, such a description is not possible, but as an image, it is possible to collectively execute it like this.

// queueModel:the queue that's holding original class objects.
// also classModel has property "OriginalClassName" and it's including class name as string
// also corresponding classes are ready for new objects.

string className;
object obj = null;

do
{
    var jObject = JObject.Parse(queueModel.Peek());
    className = jObject["OriginalClassName"].ToString();
    **className** obj = JsonConvert.DeserializeObject<**className**>(queueModel.Dequeue());
    //If you specify it manually, it will look like this
    // SomeClass obj = JsonConvert.DeserializeObject<SomeClass>(queueModel.Dequeue());

} while (queueModel.Count != 0);
Decors
  • 9
  • 3
  • 2
    What are you *really* trying to do? Say if you could write `dynamic obj = JsonConvert...`, What would you do with it? How would you know what methods/properties to use if the type could be anything? – JonasH Feb 28 '23 at 10:39
  • That would kind of defeat the entire point of the type system.... – Zohar Peled Feb 28 '23 at 10:44
  • I already have classes for them. – Decors Feb 28 '23 at 10:53
  • Sounds like a job for [Reflection](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection) – Chris Pickford Feb 28 '23 at 11:03
  • Seeing as how you're using Newtonsoft.Json, I'd recommend you create a common base class for your models and use [this](https://stackoverflow.com/q/19307752/9363973) Q&A to solve your problem. Alternatively, you could use [this](https://stackoverflow.com/q/232535/9363973) Q&A to use reflection to call `JsonConvert.DeserializeObject` with the appropriate type parameter. – MindSwipe Feb 28 '23 at 12:05
  • probably transfering class objects are just bad idea. (It's not must in my case) I just wanted to create them as class for exercise and afterward this things happend. Anyway i will look into reflection thing. Thanks. – Decors Feb 28 '23 at 12:15

0 Answers0