Is it possible in runtime to create a class from DataTable where ColumnName will be dynamic-class properties?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
With C# 4, you can do this
Not recommending it or anything, but it shows you it is possible.
Reading your comments, I undestood your mean. Just use Generics: using List fields to generate the objects. The code is quite simple:
Yes (using Reflection.Emit), but it's a bad idea.
What are you trying to do?
I am going to be looking into the ExpandoObject that was mentioned (I voted for that solution by the way as it seems easier) but yes, it is possible. I'm building a class in one of my projects where a third party utility requires a CSV line to be defined as a class.
You can build the code (I included \r\n so that I could read the resultant code):
...
... Like I mentioned, If I had to do it over again I would investigate the ExpandoObject but it is definitely possible to create a class from a DataTable. You would need to interrogate the column names to build your fields; my example had the list of column names provided from a "," delimited string.
My example is from a very specific use case but it should be enough to get you going should the ExpandoObject not work for you.
If you have C# 4 you can make use of the new dynamics feature and the
ExpandoObject
. You can read a tutorial about it here.