运行时的C#动态类? [英] C# dynamic classes at run-time?

查看:121
本文介绍了运行时的C#动态类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我不是在谈论新的动态关键字n C#4.0。 :)我相信我需要另一种方式...



我想要一个类,在代码/设计时,是从一组XML文件生成的,或文件/文件夹组合等。任何我可以做的改变外部源。



C#可以这样吗?我知道有些设计时可能会混淆某些隐藏的类名或某​​些东西(即每个项目的内置属性)。



有更简单的方法做这个?几乎像一个动态枚举?这是我要做的:

  public static class MenuItems 
{
}

在设计时,我希望基于XML添加的属性(或方法/字段,如果这更容易)文件定义。喜欢:

 < MenuItems> 
< Item>首页< / Item>
< Item>投资组合< / Item>
< Item>关于< / Item>
< Item>联系人< / Item>
< / MenuItem>

然后,在设计器中编码时,我会有如下智能感觉:

  if(page.ToString == MenuItems.Homepage)... 
if(page.ToString == MenuItems.Portfolio)... $ b注意如何在XML中定义属性,并在设计时添加到类中?



提前感谢

解决方案

您可以使用 T4模板来生成源代码。它得到了Microsoft的良好支持,并被用于多个项目,包括ASP.NET MVC,以及即将推出的ADO.NET实体框架。


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!

解决方案

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.

这篇关于运行时的C#动态类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆