2009-11-24 115 views
6

在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 ... 
+0

有没有C#3.5,我想你的意思是C#3下.NET 3.5 – Greg 2009-11-24 18:41:33

+0

你觉得这是VB6? – ChaosPandion 2009-11-24 18:41:33

+0

@Greg:我修复了主题行中的版本号:) – 2009-11-24 18:42:55

回答

5

不,不存在扩展运营商(或属性等) - 只有扩展方法

C#团队已经考虑了 - 有各种有趣的事情一个可以做(想象延伸构造函数) - 但它不是在C#3.0或4.0。有关更多信息,请参见Eric Lippert's blog(如往常一样)。

+0

他们不打算将扩展属性添加到c#4.0 ?为什么它留下了 – 2009-11-24 18:43:58

+0

@sztomi:?我不知道它曾经被“计划” - 这是“讨论”,但是,这不是一回事当然,*力量*已计划 - 我不是方C#团队的内部规划会议:) – 2009-11-24 18:46:56

2

不幸的是C#不允许运营商添加到您不拥有任何类型。你的扩展方法与你将要获得的近似。

0

什么你想在你的例子做(从字符串定义一个隐含的操作INT)是不允许的。

由于操作(隐性或显性)只能在目标或指定类的类定义来定义,不能定义框架类型之间你自己的操作。

+0

即使是允许的,从字符串到int的隐式转换会是这样了噩梦。隐式转换通常只在转换为类型时才会涉及任何信息丢失(例如:int - > long)。 – Greg 2009-11-24 18:52:15

0

我想最好的办法是这样的:

public static Int32 ToInt32(this string value) 
{ 
    return Int32.Parse(value); 
} 
2
/// <summary> 
    /// 
    /// Implicit conversion is overloadable operator 
    /// In below example i define fakedDouble which can be implicitly cast to touble thanks to implicit operator implemented below 
    /// </summary> 

    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 

     } 

    }