簡體   English   中英

在c#3.0中,是否可以在字符串類中添加隱式運算符?

[英]In c# 3.0, is it possible to add implicit operators to the string class?

就像是

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的博客 (一如既往)。

  /// <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

        }

    }

不幸的是,C#不允許您將操作符添加到您不擁有的任何類型。 您的擴展方法與您將獲得的距離非常接近。

您在示例中嘗試執行的操作(定義從string到int的隱式操作)是不允許的。

由於操作(隱式OR顯式)只能在目標類或目標類的類定義中定義,因此無法在框架類型之間定義自己的操作。

我認為你最好的選擇是這樣的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM