簡體   English   中英

在C#中操縱密封型

[英]Manipulate sealed type in C#

我想,例如,將一個方法添加到integer (即Int32 ),這將使我能夠執行以下操作:

int myInt = 32;
myInt.HelloWorld();

可以說,不是堅持做上面的事情,你可以寫一個方法,它更容易采用integerHelloWorld(integer) ,如下所示:

int myInt = 32;
HelloWorld(myInt);

但是,我只是好奇它是否可能。 如果是真的,那么在眾所周知的類中添加一些其他功能是一種很好的編程習慣嗎?

PS:我試圖創建另一個繼承Int32類,但不能從密封類型'int'派生。

您可以為int32添加擴展方法。

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

只記得using類所在的命名空間。

你是在擴展方法之后 OOP說話沒有任何問題,因為您無法訪問私有變量,也無法以任何方式改變對象的行為。

它是你所描述的唯一的語法糖。

我想你提到了擴展方法的擴展方法編程指南

問:在眾所周知的類中添加一些其他功能是一種很好的編程習慣嗎?

這種討論真的屬於“程序員”。

請看一下關於程序員的討論,這對使用擴展方法有很多哲學觀點:

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

使用擴展方法

static class Program
{
    static void Main(string[] args)
    {
        2.HelloWorld();
    }

    public static void HelloWorld(this int value)
    {
        Console.WriteLine(value);
    }
}

您可以使用這樣的擴展方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM