Currently I useDynamicInvokewhich is very slow. Still using theDelegatetype how can I directly invoke the Delegate without late-binding/theDynamicInvoke?
Delegate _method;
_method.DynamicInvoke(_args);
Thanks.
The open source framework Impromptu-Inteface adds an extension method to Delegate called FastDynamicInvoke that runs a little over 20 times faster than DynamicInvoke by using the DLR instead of reflection.
using ImpromptuInterface
...
_method.FastDynamicInvoke(_args);
Invoke is faster, but it's a bit "hidden". From MSDN on Delegate class
The common language runtime provides
an Invoke method for each delegate
type, with the same signature as the
delegate. You do not have to call this
method explicitly from C#, Visual
Basic, or Visual C++, because the
compilers call it automatically. The
Invoke method is useful in reflection
when you want to find the signature of
the delegate type.
What this means is that when you create a delegate type, the Invoke member is added with the correct signature by the compiler. This allows calling without going through DynamicInvoke
In c#, you use this like:
_method(_args);
//or
_method(typedArg1, typedArg2, andSoOn);
calling it as you would a normal method. This actually calls Invoke, which should be much faster for you.
Related
As part of my application I have a function that receives a MethodInfo and need to do specific operations on it depending if that method is "Extension Method".
I've checked the MethodInfo class and I could not find any IsExtension property or flag that shows that the method is extension.
Does anyone knows how can I find that from the method's MethodInfo?
You can call the IsDefined method on the MethodInfo instance to find this out by checking to see if the ExtensionAttribute is applied to the method:
bool isExtension=someMethod.IsDefined(typeof(ExtensionAttribute),true);
Based on
F# extension methods in C#
it seems there is an attribute on the compiled form. So see if the method has this attribute:
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.extensionattribute.aspx
This looks very similar to an earlier question, might be worth a look. The suggestion there was to look for classes and methods with the ExtensionAttribute which sounds like what you are after.
If you know you are getting a MethodInfo from an instance, you can easily check if the method is static. Extension methods are just syntactic sugar and get transformed into static method calls passing in the instance.
Doesn't the compiler switch all extension methods into static method calls at compile time?
myList.First();
becomes
Enumerable.First(myList);
If this is the case, then there are no extension methods in the .net runtime (where you are reflecting).
Why does the .NET framework specify standard delegates? Declaring a new delegate type is simple and can be done in one line of code.
public delegate void Something<T>(T obj);
Why do they define all these other types (Action, Action, etc.)?
What is the purpose and what was to be gained by this?
http://msdn.microsoft.com/en-us/library/system.action.aspx
Another thing that I wonder about is that they then go on to define 17 versions that are all the same except they take different numbers of type parameters. But why stop at 17? What informs that type of decision?
Because they wanted to expose some delegate definitely for the TPL as well as Linq, so they created Action, Action<T> and Func<> delegates.
Enumerable class uses Func<> in number of methods.
Task class was built on top of Func<> as well as Action<> delegates only.
When they expose the Linq in FW it is necessary to declare the delegates like Predicate kind of delegate which should operate with Where clauses and so forth. You can declare your own delegate in single line. but the point is you can't pass your delegate to framework method, since framework don't have your delegate at compile time.
So framework developers decided to add these standard delegates in the .Net framework itself.
Note:You could pass your own delegates to "BCL" types as System.Delegate type and they can use DynamicInvoke method to invoke it but that is an overkill. It requires boxing/unboxing when dealing with "ValueTypes" that degrades the performance, not only that DynamicInvoke itself poor performing candidate.
If one piece of code declares:
public delegate void SingleArgumentMethod<T>(T obj);
DoSomething(SingleArgumentMethod<int> thingDoDo);
and some other code declares:
public delegate void OneArgumentMethod<T>(T obj);
PerformAction(OneArgumentMethod<int> theAction);
then because SingleArgumentMethod<int> and a OneArgumentMethod<int> will be unrelated types, there will be no nice way for DoSomething to pass its received delegate to PerformAction. Instead it will have to produce an instance of OneArgumentMethod<int> using the method pointer(s) and target(s) from thingToDo, and pass that to PerformAction. If, however, both methods had used same delegate definition, such complication wouldn't be necessary and DoSomething could simply call PerformAction(thingToDo);.
I could not find a direct answer to this question yet in SO. Is there a predefined delegate with void (void) signature?
Action has the signature you're looking for. However, it doesn't mean the same thing as Runnable does: Runnable generally indicates that the run() method is intended to be run on a Thread, while Action makes no indication. For that you'd want ThreadStart, which has the same signature, and does make that indication.
If all you need is a delegate with no parameters, Action is what you want. If you're dealing with threads and need to indicate the start method, use ThreadStart.
Nope. C# handles threads differently to Java. In Java, the Runnable interface is an alternative to subclassing Thread, but you still have to create a new Thread object, passing the Runnable to a constructor.
Rather than subclassing the Thread class, you simply create a new System.Threading.Thread object and pass it a ThreadStart delegate (this is the function where you do the work). ThreadStart is the exact C# equivalent to Java's Runnable.
However, the Action delegate has the void parameters you speak of.
The Action delegate is a void with no parameters.
http://msdn.microsoft.com/en-us/library/system.action.aspx
There are also other signatures with up to 16 parameters.
In PHP, I can try to call any method that might exist on an object like this:
$object->{$method}();
Where $object is our PHP Object and $method is the name of the method that we want to call. I can dynamically call any method this way.
Is there any C# equivalent to this? Or am I just "doing it wrong"? I have a plugin/module loaded in via Reflection and I'd like to call a method on it that is not defined in the interface.
Thanks!
Contrary to PHP, C# is a statically typed language meaning that types need to be known at compile time. Although such method has been introduced in C# 4.0. It's the dynamic keyword. It allows you to declare a variable of a dynamic type and call whatever method you like on it and the compiler won't protest. The resolution will be done at runtime:
dynamic obj = FetchInstanceFromSomewhere();
obj.Method();
Another more classic method is to use reflection but this could quickly turn into a nightmare.
As answered here, C#4 has the dynamic keyword, that does dynamic method invoking.
If you are on an older version, you can do this using Reflection, but I think it is the wrong way of doing it. The C# way of doing it would be to ensure the plugin loaded has an interface, which contains the methods you need to call.
Anyways, if you need to do it using reflection, here is an example:
Type type = instance.GetType();
MethodInfo m = type.GetMethod("MethodName");
m.Invoke(instance, new object[] {});
This is for a public method taking no arguments.
I have a plugin/module loaded in via
Reflection and I'd like to call a
method on it that is not defined in
the interface
Be carefull though... The cited sentence let me guess that you are doing something wrong. Using reflection 'to the rescue' is a common misconception of many c# users. If the interface in the module was designed without the method you wish to call then there was probably a good reason for this decision. If the module was designed properly you should not be able to call this method anyway - it is either private or internal.
I wrote an extension method for String to get a char argument, string.Remove(char). But when I used this, it instead called the default string.Remove(int) method.
Shouldn't the presence of an actual method have higher priority than an implicit conversion?
Instance methods have priority over extension methods. Your observation is proof of the same.
When resolving which method to call, it will always pick a matching instance method over an extension method... which is intuitive in a way.
Paraphrased from C# in depth,
When the compiler sees that you're
trying to call a method which looks
like an instance method but is unable
to find one, it then looks for
extension methods (that are visible
based on your using directives). In
case of multiple candidates as the
target extension method, the one with
"better conversion" similar to
overloading (e.g. if IChild and IBase
both have a similar extension method
defined.. IChild.ExtensionMethod is
chosen)
Also a hidden code-breaker could be lets say TypeA didn't have SecretMethod as an instance method in Libv1.0. So you write an extension method SecretMethod. If the author introduces an instance method of the same name and signature in v2.0 (sans the this param), and you recompile your source with the latest-n-greatest Libv2.0, all existing calls to the extension method would silently now be routed to the new instance method.
This behavior is correct. The reason is that introducing an extension method should not change the way existing code executes. Code should behave exactly the same with or without this "superfluous" extension method. It may seem counter-intuitive in certain cases (like yours), but happens for a reason.