“直接”是指大小* 2(不起作用),而不是:
size1 = new Size(size1.Width * 2, size1.Height * 2);
答案 0 :(得分:4)
您可以从技术上编写扩展方法:
public static class Extensions {
public static Size Multiply(this Size size, double factor) {
return new Size((int)(size.Width * factor), (int)(size.Height * factor));
}
}
但几乎没有人会正确使用它。他们会写
this.Size.Multiply(1.2);
而不是必需的
this.Size = this.Size.Multiply(1.2);
几乎不可避免的错误,因为它看起来像一个实例方法。所以不要这样做,只需编写一个静态辅助方法。
答案 1 :(得分:3)
您可以重载*运算符:
class Size
{
public int Width { get; set; }
public int Height { get; set; }
public Size(int w, int h)
{
this.Width = w;
this.Height = h;
}
public static Size operator *(Size s, int n)
{
return new Size(s.Width * n, s.Height * n);
}
}
现在你可以做到:
Size s1 = new Size(1, 2);
Size s = s1 * 2; // s.Height = 2, s.Width = 4
答案 2 :(得分:2)
由于Size struct没有实现*运算符,因此您必须创建一个。但是使用扩展方法,无法创建新的运算符。相反,您可以创建一个名为multiply的扩展方法。
答案 3 :(得分:0)
不是没有工作,但重载运算符很容易
请参阅demo of operator overloading on codeproject
见右下角:
public static MySize operator +(MySize mySize, Int32 value)
{
return new MySize(
mySize.m_Width + value,
mySize.m_Height + value);
}
你应该花很长时间来计算*运算符重载