vb.net - Dynamic method calling in VB without reflection -
i want format numeric type using method call so:
option infer on option strict off imports system.runtime.compilerservices namespace gpr module gprextensions <extension()> public function togprformattedstring(value) string ' use vb's dynamic dispatch assume value numeric dim d double = cdbl(value) dim s = d.tostring("n3") dim dynamicvalue = value.tostring("n3") return dynamicvalue end function end module end namespace
now, various discussions around web (vb.net equivalent c# 'dynamic' option strict on, dynamic keyword equivalent in vb.net?), think code work when passed numeric type (double, decimal, int, etc). doesn't, can see in screenshot:
i can explicitly convert argument double , .tostring("n3")
works, calling on supposedly-dynamic value
argument fails.
however, can in c# following code (using linqpad). (note, compiler won't let use dynamic
parameter in extension method, maybe part of problem.)
void main() { console.writeline (1.togprformattedstring()); } internal static class gprextensions { public static string togprformattedstring(this object o) { // use vb's dynamic dispatch assume value numeric var value = o dynamic; double d = convert.todouble(value); var s = d.tostring("n3").dump("double tostring"); var dynamicvalue = value.tostring("n3"); return dynamicvalue; } }
so gives? there way in vb call method dynamically on argument function without using reflection?
to explicitly answer "is there way in vb call method dynamically on argument function without using reflection?":
edit: i've reviewed il disassembly (via linqpad) , compared code of callbyname
(via reflector) , using callbyname
uses same amount of reflection
normal, option strict off
late binding.
so, complete answer is: can option strict off
object
references, except method you're trying exists on object
itself, can use callbyname
same effect (and, in fact, doesn't need option strict off
).
dim dynamicvalue = callbyname(value, "tostring", calltype.method, "n3")
nb not equivalent late binding call, must cater possibility "method" a(n indexed) property, calls equivalent of:
dim dynamicvalue = callbyname(value, "tostring", calltype.get, "n3")
for other methods, double.compareto
.
details
your problem here object.tostring()
exists , code not attempting dynamic dispatch, rather array index lookup on default string.chars
property of string
result value.tostring()
call.
you can confirm happening @ compile time trying value.tostring(1,2)
, prefer attempt runtime lookup 2 parameter tostring
, in fact fails with
too many arguments 'public readonly default property chars(index integer) char'
at compile time.
you can confirm other non-shared
object
methods called directly callvirt
, relying upon overrides
available, not dynamic dispatch calls microsoft.visualbasic.compilerservices.newlatebinding
namespace, if review compiled code in il.
Comments
Post a Comment