在C#中操纵密封型

时间:2012-08-10 15:22:17

标签: c# oop inheritance extension-methods

例如,我希望向integer添加一个方法(即Int32),这样我就可以执行以下操作:

int myInt = 32;
myInt.HelloWorld();

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

int myInt = 32;
HelloWorld(myInt);

然而,我只是好奇它是否可能。如果是,那么良好的编程习惯是否可以为众所周知的类添加一些其他功能?

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

6 个答案:

答案 0 :(得分:10)

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

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

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

答案 1 :(得分:3)

你在Extension Methods之后。 OOP说话没有任何问题,因为您无法访问私有变量,也无法以任何方式改变对象的行为。

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

答案 2 :(得分:3)

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

答案 3 :(得分:2)

问:对于众所周知的类添加一些其他功能,这是一个很好的编程习惯吗?

这种讨论真的属于'程序员'。

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

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

答案 4 :(得分:1)

使用扩展程序方法

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

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

答案 5 :(得分:1)

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

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