Question: I want to call a generic function, defined as:
Public Shared Function DeserializeFromXML(Of T)(Optional ByRef strFileNameAndPath As String = Nothing) As T
Now when I call it, I wanted to do it with any of the variants below:
Dim x As New XMLserialization.cConfiguration
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of x)()
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(GetType(x))()
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of GetType(x))()
But it doesn't work. I find it very annoying and unreadable having to type
x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of XMLserialization.cConfiguration)()
Is there a way to call a generic function by getting the type from the instance ?
A generic type is a single programming element that adapts to perform the same functionality for a variety of data types. When you define a generic class or procedure, you do not have to define a separate version for each data type for which you might want to perform that functionality.
The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
Generic functions are functions declared with one or more generic type parameters. They may be methods in a class or struct , or standalone functions. A single generic declaration implicitly declares a family of functions that differ only in the substitution of a different actual type for the generic type parameter.
It sounds to me like you want to create a shorter alias for your XMLserialization.cConfiguration
type. Try using the Imports
statement to accomplish this:
' at the top of the file
Imports C = XMLserialization.cConfiguration
' somewhere in the body of the file
Dim x = XMLserialization.XMLserializeLDAPconfig.DeserializeFromXML(Of C)()
Generics and reflection make very poor friends. However, you can do this via MakeGenericMethod. However, that is going to be hard and ugly.
Since XmlSerializer
is based around Type
instance - I would reverse things: have the realy code Type
based, and call into that from the shallow generic version; example in C#:
public T DeserializeFromXML<T>(string path) {
return (T)DeserializeFromXML(typeof(T), path);
}
public object DeserializeFromXML(Type type, string path) {
//TODO: real code
}
Only using the methods of the System.Reflection
namespace, which really isn't worth it for the effort you're trying to save.
The type of a generic method is determined at compile time, which is why you can't set it using a variable. This is a key difference between generic programming and type reflection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With