在c#3.0中,是否可以将隐式运算符添加到字符串类中?

就像是

public static class StringHelpers { public static char first(this string p1) { return p1[0]; } public static implicit operator Int32(this string s) //this doesn't work { return Int32.Parse(s); } } 

所以:

 string str = "123"; char oneLetter = str.first(); //oneLetter = '1' int answer = str; // Cannot implicitly convert ... 

不,没有扩展操作符(或属性等) – 只有扩展方法

C#团队已经考虑过了 – 可以做各种有趣的事情(想象扩展构造函数) – 但它不在C#3.0或4.0中。 有关更多信息,请参阅Eric Lippert的博客 (与往常一样)。

不幸的是,C#不允许您将操作符添加到您不拥有的任何类型。 您的扩展方法与您将获得的距离非常接近。

  ///  /// /// Implicit conversion is overloadable operator /// In below example i define fakedDouble which can be implicitly cast to touble thanks to implicit operator implemented below ///  class FakeDoble { public string FakedNumber { get; set; } public FakeDoble(string number) { FakedNumber = number; } public static implicit operator double(FakeDoble f) { return Int32.Parse(f.FakedNumber); } } class Program { static void Main() { FakeDoble test = new FakeDoble("123"); double x = test; //posible thanks to implicit operator } } 

您在示例中尝试执行的操作(定义从string到int的隐式操作)是不允许的。

由于操作(隐式OR显式)只能在目标类或目标类的类定义中定义,因此无法在框架类型之间定义自己的操作。

我认为你最好的选择是这样的:

 public static Int32 ToInt32(this string value) { return Int32.Parse(value); }