In c# 3.0, is it possible to add implicit operator

2020-04-04 12:52发布

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

标签: c# implicit
5条回答
家丑人穷心不美
2楼-- · 2020-04-04 13:00

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. See Eric Lippert's blog for more information (as always).

查看更多
不美不萌又怎样
3楼-- · 2020-04-04 13:03

Unfortunately C# does not allow you to add operators to any types that you don't own. Your extension method is about as close as you are going to get.

查看更多
来,给爷笑一个
4楼-- · 2020-04-04 13:08

I am thinking your best bet is something like this:

public static Int32 ToInt32(this string value)
{
    return Int32.Parse(value);
}
查看更多
孤傲高冷的网名
5楼-- · 2020-04-04 13:10

What you are trying to do in your example (defining an implicit operation from string to int) is not allowed.

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.

查看更多
狗以群分
6楼-- · 2020-04-04 13:17
  /// <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

        }

    }
查看更多
登录 后发表回答