System.Drawing.Graphics 的默认构造函数是如何移除的?
当我尝试创建 Graphics 对象时,为什么以下不起作用?
System.Drawing.Graphics graphicsObj = new System.Drawing.Graphics();
(我知道我可以创建一个 private System.Windows.Forms.Panel Obj;
然后执行 CreateGraphics()
如果我想让它工作)
我试图找到图形的自定义构造函数,但我找不到。微软在哪里定义了它,或者它是如何阻止它的?
When I try to create an object of Graphics, why doesn't the following work?
System.Drawing.Graphics graphicsObj = new System.Drawing.Graphics();
(I am aware that I could create a private System.Windows.Forms.Panel Obj;
and then do CreateGraphics()
if I wanted it to work)
I tried to find a custom constructor for Graphics, but I couldn't find one. Where did Microsoft define it, or how did it block it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当没有其他声明的构造函数时,C# 编译器才会创建默认构造函数。在这种情况下,看起来所有构造函数都是内部或私有的。基本上你不会自己构建一个 - 你从图像、控件或其他任何东西中请求一个,或者为绘制事件等获得一个。
Default constructors are only created by the C# compiler if there are no other declared constructors. In this case it looks like all constructors are internal or private. Basically you don't construct one yourself - you ask for one from an image, control or whatever, or get given one for paint events etc.
直观上显而易见的是,Graphics 不能有默认构造函数。你总是希望你画的东西在某个地方可见。默认构造函数无法选择绘图的目标。
获取 Graphics 对象的方法:
Graphics.FromImage()
。您将绘制位图。常见于调整图像大小或创建“画布”时。Control.CreateGraphics()
。让您直接在屏幕上绘图。总是错误,而是使用:Graphics.FromHdc()
。在低级 P/Invoke 代码中使用,绘制到 Windows 的设备上下文。Graphics.FromHwnd()
。如上所述,直接绘制到本机窗口。总之:
FromImage()
绘制到位图It is intuitively obvious that Graphics cannot have a default constructor. You always want what you draw to be visible somewhere. A default constructor could not select the destination of the drawing.
Ways to get a Graphics object:
Graphics.FromImage()
. You'll draw into a bitmap. Common when resizing images or to create a "canvas".Control.CreateGraphics()
. Let's you draw directly to the screen. Always wrong, instead use:Graphics.FromHdc()
. Use in low-level P/Invoke code, draws to a Windows' device context.Graphics.FromHwnd()
. As above, draws directly to a native window.In summary:
FromImage()
微软没有给出Graphics对象的构造函数。创建实例的唯一方法是通过静态方法,例如 CreateGraphics() 或 FromImage()。这就是为什么你的代码不起作用。另外,作为旁注,不能继承 Graphics 对象。
Microsoft did not give the Graphics object constructors. The only way to create an instance is through the static methods, such as CreateGraphics() or FromImage(). That is why your code does not work. Also, as a sidenote, the Graphics object cannot be inherited from.