How to create two classes with the same methods, even one of them not being 'Partial'?

1

Can I create a class to implement the System.Console class, without creating extensions? Example:

'A original, da mscorlib:
Public NotInheritable Class Console
    (...)
End Class

It is marked as a non-partial class, so ... you can not just:

Partial Public NotInheritable Class Console
    /*.....*/
End Class

Extensions do not work because it is NotInheritable

If I try to make a clone of it? For example:

Public NotInheritable Class Console
    Public Sub WriteLine(ByVal arg As String)
        System.Console.WriteLine(arg) ' Irá dar uma stack overflow...
    End Sub
End Class

How can I then do two Console classes? Keeping the methods?

    
asked by anonymous 02.05.2015 / 06:41

1 answer

1

You are confusing some concepts here. The class declared as NotInheritable means that no class can inherit from it ( abstract in C #). Inheritance is a basic concept of Object Oriented Programming and is much broader than an extension.

Partial Classes is a .NET Framework feature and is nothing more than separating the same class into more than one file. At the end of the day you have only one class, with members logically divided. This is very useful in event-based applications such as Windows Form and ASP.NET WebForms, where controls are declared in one file and the logic of UI manipulation in another, but both are the same class.

As for your question you can not "extend" a class this way, but if you want to create a clone it is possible using another namespace :

Namespace Sistema
    Public Class Console
        Public Shared Sub WriteLine(ByVal arg As String)
            System.Console.WriteLine(arg)
        End Sub
    End Class
End Namespace

Then you can use it like this:

Module Module1
    Sub Main()
        Sistema.Console.WriteLine("Hello World")
    End Sub
End Module

OR

If you really want to override the System methods, then you must remove its references from the project. Create a console application and remove all references (in the project properties):

SetthenamespacerootasSystem:

And hence the code. Keep in mind that this way all the features of System have been lost, you will have to actually rewrite them:

Public Class Console
    Public Shared Sub WriteLine(ByVal arg As String)
        ' código da sua implementação de escrita no console
    End Sub
End Class
    
02.05.2015 / 15:52