creating delegate instance from method retrieved through reflection

P

Pieter Breed

Hi All,

I am trying to use the attribute/reflection system to as much
potential as I can think of, but I've run into a snag. I would
appreciate it if someone would point me in the right direction.

First my question: How am I supposed to make instances of delegates
when I have the method (that I want to make the delegate of) retrieved
through reflection?

My situation is like this:

* I have one delegate declaration:
delegate void TopLevelDelegate( );

* I have two Attributes:
class TopLevelAttribute : Attribute
{
private string mDescription;
public TopLevelAttribute( string desc )
{
mDescription = desc;
}

public string Description { get { return mDescription; } }
}

class ContainsTopLevelAttribute : Attribute
{
}

* An example of how I would like to use it is as follows:
[ContainsTopLevel()]
class Foo
{
[TopLevel("Bar")]
static void SomeMethod()
{
}
}

* somewhere I have a method that looks like this:
bool AddDelegateInstance( string description, TopLevelDelegate tld );

* And finally here is where I have a problem. I am trying to iterate
through all of this assembly's classes and find types that are
annotated with ContainsTopLevelAttribute, Then for those classes I
want to look for all methods which are annotated with
TopLevelAttribute. This is what I tried:
private static void findAllTopLevels()
{
Assembly thisAssembly = Assembly.GetExecutingAssembly();
Type[] types = thisAssembly.GetTypes();
foreach ( Type classType in types )
foreach ( Attribute classAtr in classType.GetCustomAttributes(
typeof(ContainsTopLevelAttribute), false ) )
{
ContainsTopLevelAttribute ctla = classAtr as
ContainsTopLevelAttribute;
if ( ctla != null )
foreach ( MethodInfo mi in classType.GetMethods() )
foreach( Attribute methodAtr in mi.GetCustomAttributes(
typeof( TopLevelAttribute ), false ) )
{
TopLevelAttribute tla = methodAtr as TopLevelAttribute;
if ( tla != null )
{
// ERROR RIGHT BELOW HERE
AddDelegateInstance( tla.Description, new
TopLevelDelegate( mi.Name ) );
}
}
}
}

* I get the following error:
error CS0118: 'System.Reflection.MemberInfo.Name' denotes a 'property'
where a 'method' was expected

* I will repeat my question: How am I supposed to make instances of
delegates when I have the method retrieved through reflection?

Friendly Regards
Pieter Breed
 
J

Jon Skeet [C# MVP]

* I will repeat my question: How am I supposed to make instances of
delegates when I have the method retrieved through reflection?

Use Delegate.CreateDelegate(Type, MethodInfo)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top