如何为设计器之类的对象生成实例化代码? [英] How do I generate instantiation code for object like designer?

查看:75
本文介绍了如何为设计器之类的对象生成实例化代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

VisualStudio中的设计器为各种GUI对象生成代码,如下所示:

The designer in VisualStudio generates code for various GUI objects, like this:

. . .
this.textBox.MaxChars = 1000;
this.textBox.Name = "textBox";
this.textBox.Size = new System.Drawing.Size(168, 235);
. . .



我的应用程序中是否存在访问此功能的问题?也就是说,将一个对象传递给一些神奇的方法并返回一个包含生成对象的代码的字符串数组?



我知道我可以自己做很多对反射类的调用,但我希望这是一个已经解决的问题。这是针对C#2.0(VS 2005)。



为什么? (响应澄清要求):



我最近向CodeProject提交的项目之一(Spiral TrackBar控件)包括一个应用程序(SpiralTrackBarExplorer),它允许您设置控件的所有成员并以交互方式查看结果并使用控件进行播放。



有一个为此控件生成代码按钮会很不错然后可以将其剪切并粘贴到用户的应用程序中。



非常感谢提前,

格雷厄姆


Is there anyway in my application to access this functionality? That is, pass an object to some magical method and get in return an array of strings containing the code to generate the object?

I know I could do this myself with lots of calls to the reflection classes, but I'm hoping that this is an already solved problem. This is for C# 2.0 (VS 2005).

Why? (in response to the requests for clarification):

One of my recently submitted projects to CodeProject (the Spiral TrackBar control) includes an app (SpiralTrackBarExplorer) which allows you to set all of the members for the control and see the results interactively and play with the control.

It would be nice to have a "generate code for this control" button, which could be then cut-and-paste into the user's application.

Many thanks in advance,
Graham

推荐答案

是的,它在Visual Studio中解决了。设计师是这个神奇的东西。有一篇关于这样做的旧MSDN文章这里 [ ^ ]。从实现的微不足道的事情来看FAR!





在您更新的案例中,设计师的解决方案将超越顶级。你要做的就是跟踪控件中你正在做的那些值!然后只发出一个格式化的字符串,其中包含用于设置这些值的标准代码。这样做没有任何反思。



它真的很简单:

Yeah, it's solved, inside Visual Studio. The Designer is what does this "magic". There's an old MSDN article on doing it here[^]. It's FAR from a trivial thing to implement!


In your updated case, the designer solution would be WAY over the top. What you have to do is keep track of those values in your control, which you're already doing!, and then just emit a formatted string that contains the standard code for setting those values. There's no reflection required to do that.

It's really as simple as:
StringBuilder sb = new StringBuilder();
sb.AppendFormat("\t{0}.SomeProperty = {1}", controlName, somePropertyValue);


这篇关于如何为设计器之类的对象生成实例化代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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