【问题标题】:Manipulate sealed type in C#在 C# 中操作密封类型
【发布时间】:2012-08-10 15:22:17
【问题描述】:

例如,我想向integer 添加一个方法(即Int32),这将使我能够执行以下操作:

int myInt = 32;
myInt.HelloWorld();

可以说,您可以编写一个采用integerHelloWorld(integer) 的方法,而不是坚持执行上述操作,如下所示,更容易:

int myInt = 32;
HelloWorld(myInt);

但是,我只是好奇这是否可能。如果属实,那么向知名类添加一些其他功能是否是一种良好的编程习惯

PS:我尝试创建另一个从Int32继承的类,但不能从密封类型“int”派生。

【问题讨论】:

  • 我想你想要扩展方法
  • 虽然扩展方法可以做到这一点(正如其他人指出的那样),但我建议您不要对像“int”这样的基本类型这样做。对于一年后查看您的代码并想知道数字 32 与 World.SayHello(32) 之类的东西打招呼意味着什么的维护工程师来说,这不太直观。扩展方法的直观感觉是扩展对象正在做某事,但数字应该积极做的事情很少。

标签: c# oop inheritance extension-methods


【解决方案1】:

您可以为int32添加扩展方法。

   public static class Int32Extensions
   {
       public static void HelloWorld(this int value) 
       {
         // do something
       }
   }

记住using类所在的命名空间。

【讨论】:

    【解决方案2】:

    我想你提到了扩展方法programming guide of extension method

    【讨论】:

      【解决方案3】:

      你在关注Extension Methods。 他们在面向对象编程方面没有任何问题,因为您无法访问私有变量,也无法以任何方式更改对象的行为。

      它是您准确描述的唯一语法糖。

      【讨论】:

        【解决方案4】:

        问:向知名类添加一些其他功能是一种好的编程习惯吗?

        这种类型的讨论确实属于“程序员”。

        请看一下这个关于程序员的讨论,其中有很多关于使用扩展方法的哲学观点:

        https://softwareengineering.stackexchange.com/questions/77427/why-arent-extension-methods-being-used-more-extensively-in-net-bcl

        还有:

        https://softwareengineering.stackexchange.com/questions/41740/when-to-use-abstract-classes-instead-of-interfaces-and-extension-methods-in-c?lq=1

        【讨论】:

          【解决方案5】:

          使用扩展方法

          static class Program
          {
              static void Main(string[] args)
              {
                  2.HelloWorld();
              }
          
              public static void HelloWorld(this int value)
              {
                  Console.WriteLine(value);
              }
          }
          

          【讨论】:

            【解决方案6】:

            您可以使用扩展方法 像这样:

            public static class IntExtensions
            {
                public static string HelloWorld(this int i)
                {
                    return "Hello world";
                }
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2011-06-10
              • 2013-10-24
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-12-15
              相关资源
              最近更新 更多