所以,我有一个应用程序可以在屏幕上绘画。我用 double 操作,但要绘画,我必须使用 float 或整数。所以,像这样的事情经常发生:
g.DrawEllipse(monsterPen, new Rectangle(
(int)Math.Round(x - (double)sizeVessel * 9.0 / 20.0),
(int)Math.Round(y - (double)sizeVessel * 9.0 / 20.0),
(int)Math.Round(sizeVessel * 18.0 / 20.0),
(int)Math.Round(sizeVessel * 18.0 / 20.0)));
虽然它可能看起来像这样
g.DrawEllipse(monsterPen, NewRectangleFromD(
x - (double)sizeVessel * 9.0 / 20.0),
y - (double)sizeVessel * 9.0 / 20.0),
sizeVessel * 18.0 / 20.0,
sizeVessel * 18.0 / 20.0)));
甚至像这样
DrawCircle(g, monsterPen, x, y, sizeVessel * 9.0 / 20.0)
但是,我不确定如何更好地做到这一点。
在 C/C++ 中,如果我没记错的话,你可以做一个别名,例如这样的代码:
DrawCircle(g, p, x, y, r)
应出于所有目的被视为:
g.DrawEllipse(p, new Rectangle(
(int)Math.Round(x - r / 2.0),
(int)Math.Round(y - r / 2.0),
(int)Math.Round(r),
(int)Math.Round(r))
但我在 C# 中找不到这样的选项。由于无法强制内联(我在 .Net 4.0 中工作),我担心如果我只是声明一个这样做的 DrawCircle 方法,我会减慢我的应用程序(那些绘制调用经常完成)。
那么,在这里采取的正确方法是什么?
最佳答案
一种选择是使用 extention methods :
public static class GraphicsExtentions
{
public static void DrawEllipse(this Graphics g, Pen pen, double x, double y, double width, double height)
{
g.DrawEllipse(pen, (int)x, (int)y, (int)width, (int)height);
}
}
你这样称呼:
double x, y, w, h;
...
g.DrawEllipse(pen, x, y, w, h);
如果你想让它超快,你可以看看激进的 inlining attribute :
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void DrawEllipse(this Graphics g, Pen pen, double x, double y, double width, double height)
{
g.DrawEllipse(pen, (int)x, (int)y, (int)width, (int)height);
}
关于c# - 在 C# 中使用许多转换和明显模式缩短代码的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24840778/