繁体   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