在C#中操纵密封型

Sai*_*ait 3 c# oop inheritance extension-methods

我想,例如,添加一个方法integer(即Int32),这将使我能够做到以下几点:

int myInt = 32;
myInt.HelloWorld();
Run Code Online (Sandbox Code Playgroud)

可以说,你可以写一个方法,而不是坚持上面这样做,你可以更容易地使用integer,HelloWorld(integer)如下所示:

int myInt = 32;
HelloWorld(myInt);
Run Code Online (Sandbox Code Playgroud)

但是,我只是好奇它是否可能.如果是真的,那么在众所周知的类中添加一些其他功能是一种很好的编程习惯吗?

PS:我试图创建另一个继承自的类Int32,但不能从密封类型'int'派生.

Dan*_*ite 10

您可以为其添加扩展方法int32.

   public static class Int32Extensions
   {
       public static void HelloWorld(this int value) 
       {
         // do something
       }
   }
Run Code Online (Sandbox Code Playgroud)

只记得using该类所在的命名空间.