在C#中扩展现有结构以添加运算符

Can*_*ğlu 6 .net c# struct operator-keyword

我想扩展.NET的内置Color结构来添加像+或的新运算符-.
我将使用它们像:

Color c1 = Color.FromName("Red");
Color c2 = Color.FromName("Blue");
Color result = c2 - c1;
Run Code Online (Sandbox Code Playgroud)

可能吗?如果有,怎么样?

Pao*_*lla 8

正如其他人所建议的,您可以采用扩展方法方式或装饰器模式方式。

但是,考虑到 Color 具有相当数量的属性和方法,因此将它们全部从装饰器类重定向到包装的 Color 结构将意味着编写大量样板文件。但是,如果您走这条路,您确实可以定义运算符,甚至可以定义从您的类到 Color 的隐式转换,以及相反的方式(以便您可以更互换地使用它们),如下所示:

public class MyColor {
    public System.Drawing.Color val;

    public MyColor(System.Drawing.Color color)
    {
        this.val = color;
    }

    public static MyColor AliceBlue 
    {
        get {
            return new MyColor(System.Drawing.Color.AliceBlue);
        }
    }

    public override string ToString()
    {
        return val.ToString();
    }
    // .... and so on....

    // User-defined conversion from MyColor to Color
    public static implicit operator System.Drawing.Color(MyColor c)
    {
        return c.val;
    }
    //  User-defined conversion from Color to MyColor
    public static implicit operator MyColor(System.Drawing.Color c)
    {
        return new MyColor(c);
    }
}
Run Code Online (Sandbox Code Playgroud)

去测试:

MyColor c = System.Drawing.Color.AliceBlue; // assigning a Color to a MyColor
                                            // thanks to the implicit conversion
Console.WriteLine(c.ToString()); // writes "Color [AliceBlue]"
Run Code Online (Sandbox Code Playgroud)


asa*_*yer 7

使用内置运算符无法实现.

你可以编写一个扩展方法来伪造它:

public static class Extensions
{
    public static Color Substract(this Color color, Color theOtherColor)
    {
        //perform magic here! 
        //be sure to return something or this won't compile
    }
}

Color c1 = Color.FromName("Red");
Color c2 = Color.FromName("Blue");
Color result = c2.Subtract(c1);
Run Code Online (Sandbox Code Playgroud)