How to import objects from external, uncompiled .cs files?
Let's say I have a file named "myCustomObject.cs", and it has a class definition "customObject1".
What would the best way to programmatically load myCustomObject and instantiate a customObject1, but dynamically-so? That is: Without any static references.
I'm expecting that I have multiple objects defined in multiple files (under the same namespace, however) that I need to read and instantiate.
15 Replies
No easy way whatsoever
You would have to... dunno, read the file as text, then compile it to a DLL, then load that DLL
While... somehow ensuring that the objects conform to some common interface
Without, like, referencing that interface in those loose files... because they're loose files
What are you trying to achieve?
I've just got a bunch of objects defined in .cs files that were generated dynamically, and now i'm trying to import them dynamically.
...but yeah: Everything I've found makes it look like i'm going to have to compile them.
Well, yes, C# is a compiled language
Why did you generate those objects as loose C# files and not, dunno, JSON?
What are those objects? Just data?
I don't get a choice of how I get these objects, in this particular case.
The objects are essentially the data.
My condolences that you have to work with this shitshow, then
Yeah, it’s a weird one.
why it is need? it is impossible in compile language
only possible in run-time language(like javascript)
Objects are generated by another program and output to a .cs file that contains a Namespace with a single class that contains defined members.
I do not have any control or access over that other program/api.
As you know C# is compile language,it means can't load dynamic and run.
of cousrse you can load data from ".cs" file.but can't run it's code.
Honestly: It's fine that I can't run the code - I just need the key:value pairings of the variable declarations and definitions.
I'm learning how to use Roslyn to solve this problem.
yeah.it is posible.
I am sorry. I think it is better to use File input.
If you dont need to run it, just treat the files as text and write a parser that extracts the data you need?
I mean you could technically run it as scripts in another app using ScriptEngine and get the values
it would not be practical thou, as u would need to know which libraries to include to compile the script to run and also need to know the variables/methods u need to access to get the results.
and given what you said, it would probably be easier to just parse the cs file
yeah.you are right exactly.
If you want a hand on the parser, paste a file or two here 🙂
and tell exactly what you want extracted