C# dynamic classes at run-time?

半腔热情 提交于 2019-12-14 03:42:50

问题


First, I am not talking about the new 'dynamic' keyword n C# 4.0. :) I believe I need to go the other way...

I want a class, at code/design-time, that is generated from a set of XML files, or files/folder combinations, etc. Anything I can do with a change to the extern source.

Is this possible with C#? I know it is possible with some design-time compliation of some hidden class name or something (i.e. the built in Properties for each project).

Is there an easier way to do this? ALmost like a dynamic enum? Here's what I am trying to do:

public static class MenuItems
{
}

And at design-time, I want the properties (or methods/fields, if that's easier) added based on an XML file definition. Like:

<MenuItems>
  <Item>Homepage</Item>
  <Item>Portfolio</Item>
  <Item>About</Item>
  <Item>Contact</Item>
</MenuItem>

Then, while coding in the designer I would have intellisense like:

if (page.ToString == MenuItems.Homepage)...
if (page.ToString == MenuItems.Portfolio)...

Notice how the properties were defined in the XML, and added to the class at design time?

Thanks in advance!


回答1:


You can use T4 Templates to generate source code. It is well supported by Microsoft and is used on several projects including ASP.NET MVC, and soon the ADO.NET Entity Framework.




回答2:


If I may direct your attention to the ASP.NET Membership Provider, and the Web.sitemap, perhaps it will be of assistance to your actual problem.



来源:https://stackoverflow.com/questions/1408658/c-sharp-dynamic-classes-at-run-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!