How to create an extension method for the type of a class in VB.NET

1

I'm creating an MVC framework that will work similar to the Entity Framework inside a VB.NET project where I've created an attribute called TableAttribute that will set the table name and the schemas to the model , like this:

Namespace Models.DataAnnotations
  <AttributeUsage(AttributeTargets.Class)>
  Public Class TableAttribute : Inherits Attribute

    Sub New(Name As String)
      Me.Name = Name
    End Sub

    Public Property Name As String
    Public Property Schema As String = "dbo"

  End Class
End Namespace

So I can add it to my models that will serve to make the application data layer:

Imports Models.DataAnnotations
Namespace Models
  <Table("Usuario", Schema:="Sistema")>
  Public Class UsuarioModel
    Public Property Id As Integer
    Public Property Login As String
    Public Property Senha As String
  End Class
End Namespace

In addition, I have a Module that is related to Namespace.Models which holds a series of extension functions for the models:

Imports System.Reflection
Namespace Models
  Public Module ModelsExtensions
    <Extension()>
    Function GetTable(Obj as Object) as String

      Dim type As Type = Obj.GetType()
      Dim temp As TableAttribute = type.GetCustomAttributes(GetType(TableAttribute), True)(0)

      If (temp IsNot Nothing) Then Return $"{temp.Schema}.{temp.Name}"

      Return $"dbo.{type.Name}"

    End Function
  End Module
End Namespace

My problem is that, in order for me to get the name of any table, I am forced to instantiate it by making a new Usuario().GetTable() .

Is there any way I can extend a method directly to type Usuario ? The result I hope would look like this: Usuario.GetTable()

    
asked by anonymous 25.10.2018 / 17:06

1 answer

1

There is no way, after all extension methods are made to operate on an instance. If you do not want to operate on an instance then it does not make sense to do this.

You probably just want a regular static method passing the type, or it should probably be a generic method, but I can not say.

C # should have some resemblance to static extension method in version 8 or 7.

    
25.10.2018 / 17:20