2009-11-24 29 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 

     } 

    }