0

Say I have a class of type Item, and that class have property, functions, everything. I would like to make it into a generic Object with only the instance data left. I would like to remove all function, static or not. How would I do this?

Some code example:

Item testItem = new Item();
testItem.fieldA = "aaaa";
testItem.functionB("B");

// strip data
Object strippedItem = strip(testItem);

// only data is left
string a = strippedItem.fieldA;  // aaaa
strippedItem.functionB("B") // error, functionB does not exist.

I guess to some degree, this question is asking how do I automatically create struct from class without having to declare them.

Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174
  • 1
    Your question is very unclear. Are you asking to modify your source code? – SLaks Dec 13 '13 at 18:37
  • No, I would like to do this in memory, I will add some example. – Bill Software Engineer Dec 13 '13 at 18:37
  • I'm not sure I truly understand your question, but would assigning to an `object` be enough? – dee-see Dec 13 '13 at 18:37
  • If you cast something to object, you won't be able to use any of the methods and such... But if you want some kind of DTO, you should probably design a specific class for that. You could even make an anonymous type, if it's just data... – Magus Dec 13 '13 at 18:38
  • Are you asking for shallow copy? http://stackoverflow.com/questions/18066429/shallow-copy-or-deep-copy – user3096476 Dec 13 '13 at 18:40
  • Can you give a little detail about *why* you want to do this? It's kind of an odd scenario for a typed language to want to do this. – matt Dec 13 '13 at 18:41
  • For serialization. But the code I am using is crashing on my static function in my class, so I want to strip my class of functions and leave only data left, which will not cause any problem in the serialization process. And before you ask, no, I can't edit the serialization code, and I have to work around the error. – Bill Software Engineer Dec 13 '13 at 18:43
  • There is no remotely sane way to do that. You could use `ILGenerator` to duplicate the class. – SLaks Dec 13 '13 at 18:44
  • lol, alright fine, I'll try something else. – Bill Software Engineer Dec 13 '13 at 18:45
  • I found a way to do this! Don't know if you guys will think it's "sane" or not but at least it works! I basically Serialize then Deserialize to a Object! Which will strip my class of any functions and leave just the data behind!! I will post answer. – Bill Software Engineer Dec 13 '13 at 18:59

1 Answers1

0

Here is my workaround to do exactly this (warning: this solution might be insane):

           Item test = new Item();
           JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
           string jsonStr = jsonSerializer.Serialize(test);
           Object strippedItem = jsonSerializer.Deserialize<Object>(jsonStr);
Bill Software Engineer
  • 7,362
  • 23
  • 91
  • 174