C#枚举扩展方法
示例
扩展方法对于将功能添加到枚举很有用。
一种常见用途是实现转换方法。
public enum YesNo { Yes, No, } public static class EnumExtentions { public static bool ToBool(this YesNo yn) { return yn == YesNo.Yes; } public static YesNo ToYesNo(this bool yn) { return yn ?YesNo.Yes: YesNo.No; } }
现在,您可以快速将枚举值转换为其他类型。在这种情况下是布尔。
bool yesNoBool = YesNo.Yes.ToBool(); //yesNoBool==true YesNo yesNoEnum = false.ToYesNo(); //yesNoEnum==是No.No
另外,扩展方法可以用来添加类似方法的属性。
public enum Element { Hydrogen, Helium, Lithium, Beryllium, Boron, Carbon, Nitrogen, Oxygen //Etc } public static class ElementExtensions { public static double AtomicMass(this Element element) { switch(element) { case Element.Hydrogen: return 1.00794; case Element.Helium: return 4.002602; case Element.Lithium: return 6.941; case Element.Beryllium: return 9.012182; case Element.Boron: return 10.811; case Element.Carbon: return 12.0107; case Element.Nitrogen: return 14.0067; case Element.Oxygen: return 15.9994; //Etc } return double.Nan; } } var massWater = 2*Element.Hydrogen.AtomicMass() + Element.Oxygen.AtomicMass();