简体   繁体   English

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

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

something like 就像是

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);
    }
}

so : 所以:

string str = "123";
char oneLetter = str.first(); //oneLetter = '1'

int answer = str; // Cannot implicitly convert ...

No, there's no such thing as extension operators (or properties etc) - only extension methods . 不,没有扩展操作符(或属性等) - 只有扩展方法

The C# team have considered it - there are various interesting things one could do (imagine extension constructors) - but it's not in C# 3.0 or 4.0. C#团队已经考虑过了 - 可以做各种有趣的事情(想象扩展构造函数) - 但它不在C#3.0或4.0中。 See Eric Lippert's blog for more information (as always). 有关更多信息,请参阅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

        }

    }

Unfortunately C# does not allow you to add operators to any types that you don't own. 不幸的是,C#不允许您将操作符添加到您不拥有的任何类型。 Your extension method is about as close as you are going to get. 您的扩展方法与您将获得的距离非常接近。

What you are trying to do in your example (defining an implicit operation from string to int) is not allowed. 您在示例中尝试执行的操作(定义从string到int的隐式操作)是不允许的。

Since an operation (implicit OR explicit) can only be defined in the class definition of the target or destination class, you cannot define your own operations between framework types. 由于操作(隐式OR显式)只能在目标类或目标类的类定义中定义,因此无法在框架类型之间定义自己的操作。

I am thinking your best bet is something like this: 我认为你最好的选择是这样的:

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