扩展C#中的现有结构以添加运算符 [英] Extend an existing struct in C# to add operators
本文介绍了扩展C#中的现有结构以添加运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Color
结构,以添加像+
或-
这样的新运算符。我将按如下方式使用它们:
Color c1 = Color.FromName("Red");
Color c2 = Color.FromName("Blue");
Color result = c2 - c1;
有可能吗?如果是,如何?
推荐答案
无法使用内置运算符执行此操作。
您可以编写一个扩展方法来伪装它:
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);
这篇关于扩展C#中的现有结构以添加运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文