【问题标题】:In c# 3.0, is it possible to add implicit operators to the string class?在 c# 3.0 中,是否可以将隐式运算符添加到字符串类?
【发布时间】:2009-11-24 18:38:58
【问题描述】:

类似

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# 3.5,我想你的意思是.NET 3.5下的C# 3
  • 你认为这是什么 VB6?
  • @Greg:我修复了主题行中的版本号 :)
  • oouuups,对不起,我的头很痛,是的 3.0 确实 :-) 嗯,好吧似乎不可能 :-(

标签: c# implicit


【解决方案1】:

不,没有扩展运算符(或属性等)之类的东西 - 只有扩展方法

C# 团队已经考虑过 - 可以做各种有趣的事情(想象一下扩展构造函数) - 但它不在 C# 3.0 或 4.0 中。请参阅Eric Lippert's blog 了解更多信息(一如既往)。

【讨论】:

  • 他们不打算在 c# 4.0 中添加扩展属性吗?为什么被遗漏了?
  • @sztomi:我不知道它曾经被“计划”过——它被“讨论过”,但那不是一回事。当然它可能已经计划好了 - 我不是 C# 团队内部计划会议的参与者 :)
【解决方案2】:

不幸的是,C# 不允许您将运算符添加到您不拥有的任何类型。您的扩展方法几乎与您将要获得的一样接近。

【讨论】:

    【解决方案3】:
      /// <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】:

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

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

      【讨论】:

      • 即使允许,从 string 到 int 的隐式转换也将是一场噩梦。隐式转换通常仅在转换为不涉及任何信息丢失的类型时进行(例如:int -> long)。
      【解决方案5】:

      我认为你最好的选择是这样的:

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

      【讨论】:

        猜你喜欢
        • 2017-02-05
        • 2017-05-06
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        • 2011-12-21
        • 2014-07-13
        • 2021-07-25
        • 2012-09-04
        相关资源
        最近更新 更多