How do I know if an action is an anonymous method or not?

This is C # 4.0.

I have a class that stores WeakReference on some Action , like this:

 public class LoremIpsum { private Dictionary<Type, List<WeakReference>> references = new Dictionary<Type, List<WeakReference>>(); public void KeepReference<T>(Action<T> action) { if (this.references.ContainsKey(typeof(T))) { this.references[typeof(T)].Add(new WeakReference(action)); } else { this.references.Add(typeof(T), new List<WeakReference> { new WeakReference(action) }); } } } 

This class has another method that allows you to execute an Action passed to it later, but it has little value in this matter.

and I use this class as follows:

 public class Foobar { public Bar Bar { get; set; } public void Foo(LoremIpsum ipsum) { ipsum.KeepReference<Bar>((b) => { this.Bar = b; }); ipsum.KeepReference<Bar>(this.Whatever); } public void Whatever(Bar bar) { // Do anything, for example...: this.Bar = bar } } 

Bar is the third class in my application.

My question is:

In the KeepReference method, how can I find out if the Action parameter refers to an anonymous method parameter ( this.Bar = b; ) or a specific method ( this.Whatever )?

I checked the properties of Action . I could not find any property on the Action (e.g. IsAbstract ) like IsAnonymous . The main type MethodInfo makes sense, because after compilation I see in ildasm an anonymous method "became" a regular Foobar method. In ildasm, I also see that the anonymous method is not a full pink square, but a white square surrounded by a pink one, and in its definition there is a call to some CompilerServices classes, but I do not know how to use this in C #. I am sure that you can learn about the real nature of Action . What am I missing?

+4
source share
2 answers

In order to “accept” the answer to this question, I went to the link given by Michael Curling in his first comment on my question.

 if (action.Target.GetType().GetMethods().Where(method => method.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any()).Contains(action.Method)) { // ... } 
+1
source

Generated compiler methods will always have their names with angle brackets, as shown below

 Void <Main>b__0() 

so why not just get the name and see if it has brackets in brackets.

 Action someaction = () => Console.Write("test"); string methodName= RuntimeReflectionExtensions.GetMethodInfo(someaction).ToString(); if(methodName.Contains("<")) Console.write("anonymous"); 

or you can use a much better match with regex pattern

+1
source

Source: https://habr.com/ru/post/1438140/


All Articles