代码之家  ›  专栏  ›  技术社区  ›  Enriquev

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

  •  6
  • Enriquev  · 技术社区  · 16 年前

    类似的东西

    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 ...
    
    5 回复  |  直到 12 年前
        1
  •  5
  •   Jon Skeet    16 年前

    不,不存在扩展运算符(或属性等)-只有扩展 方法 .

    C团队已经考虑过了——人们可以做很多有趣的事情(想象一下扩展构造函数)——但是它不在C 3.0或4.0中。见 Eric Lippert's blog 获取更多信息(一如既往)。

        2
  •  2
  •   Andrew Hare    16 年前

    不幸的是,C不允许向您不拥有的任何类型添加运算符。你的扩展方法和你想得到的差不多。

        3
  •  2
  •   komizo    12 年前
      /// <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
    
            }
    
        }
    
        4
  •  0
  •   Greg    16 年前

    不允许您在示例中尝试执行的操作(定义从字符串到int的隐式操作)。

    由于只能在目标类或目标类的类定义中定义操作(隐式或显式),因此不能在框架类型之间定义自己的操作。

        5
  •  0
  •   ChaosPandion    16 年前

    我想你的最佳选择是这样的:

    public static Int32 ToInt32(this string value)
    {
        return Int32.Parse(value);
    }
    
    推荐文章