473,386 Members | 1,598 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

CreateDelegate(Type, Instance, MethodInfo)

Hi there,

I am working on a class library that should incpect a given class,
make a delegate to a get Property and use it later on.
Here is the code snippet:

public delegate int MyClassDelegate(MyClass cls);

....

public MyClassDelegate GetGetDelegate(MyClass cls, string memberName)
{
Type objType = cls.GetType();
PropertyInfo propInfo = objType.GetProperty(memberName);
if (propInfo != null)
{
MethodInfo methodInfo = propInfo.GetGetMethod();
if (methodInfo != null)
{
/*1*/ Type dlgType = typeof(MyClassDelegate);
/*2*/ return (MyClassDelegate)Delegate.CreateDelegate(dlgType,
null, methodInfo);
}
else
return null;
}
else
return null;
}

....

Then lather on:
ClassName cls = ...;
string memberName = ...;

ClassDelegate dlg = GetGetDelegate(cls, memberName);

foreach( ClassName c in list)
{
int x = dlg(c);
...
}

Everything works fine.

However, I would like to avoid explicit usage of MyClass and
MyClassDelegate
There is enough information in MethodInfo above to create a delegate.
So, GetGetDelegate() should be:

public Delegate GetGetDelegate(string className, string memberName)
{
Type objType = Type.GetType(className);
...

/*1*/ Type dlgType = CreateDelegateType(methodInfo);
/*2*/ return Delegate.CreateDelegate(dlgType, null, methodInfo);

...
}

The CreateDelegateType() returns the appropriate type of the
MethodInfo.
That works fine too.

But how can I use a delegate now?

Delegate dlg = GetGetDelegate(cls, memberName);

// HOW TO CALL dlg ?
Note that I use this approach mainly because of performance, as
delegate direct call is much faster than dynamic invocation.

Thank you.

Jun 27 '08 #1
1 2431
3 options depending on what version of C# and .NET (separately) you
are using; see below.

Marc
Note that I use this approach mainly because of performance, as
delegate direct call is much faster than dynamic invocation.
Just another option: http://www.codeproject.com/KB/cs/Hyp...escriptor.aspx

--code--

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Linq.Expressions; // only for .NET 3.5 version

// only for .NET 2.0/3.0 version
//public delegate TResult Func<TArg1, TResult>(TArg1 arg1);
class Foo
{
public Foo() { }
public Foo(int bar) { Bar = bar; }
private int bar;
public int Bar
{
get { return bar; }
set { bar = value; }
}
}

static class Program
{
// only for .NET 3.5 version
public static Func<TArg1, TResultGetGetDelegate35<TArg1,
TResult>(string memberName)
{
var obj = Expression.Parameter(typeof(TArg1), "obj");
var body = Expression.Property(obj, memberName);
return Expression.Lambda<Func<TArg1, TResult>>(body,
obj).Compile();
}
public static Func<TArg1, TResultGetGetDelegate20<TArg1,
TResult>(string memberName)
{
Type objType = typeof(TArg1);
PropertyInfo propInfo = objType.GetProperty(memberName);
if (propInfo != null)
{
MethodInfo methodInfo = propInfo.GetGetMethod();
if (methodInfo != null)
{
return (Func<TArg1, TResult>)Delegate.CreateDelegate(
typeof(Func<TArg1, TResult>),
null, methodInfo);
}
else
return null;
}
else
return null;
}

static void Main()
{
// C# 3, .NET 2.0 or above coded
Func<Foo, intdlg1 = foo =foo.Bar;

// .NET 3.5, dynamic
Func<Foo, intdlg2 = GetGetDelegate35<Foo, int>("Bar");

// C# 2, .NET 2.0 dynamic
Func<Foo, intdlg3 = GetGetDelegate20<Foo, int>("Bar");

List<Foolist = new List<Foo>();
list.Add(new Foo(1));
list.Add(new Foo(2));
list.Add(new Foo(3));

foreach (Foo foo in list)
{
Console.WriteLine(dlg1(foo));
Console.WriteLine(dlg2(foo));
Console.WriteLine(dlg3(foo));
}
}
}

--end code--
Jun 27 '08 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: redhotsly | last post by:
Hi, Is is possible to create an event handler method that can handle any type of event no matter what the delegate signature is. Here is the code I have so far: public class class1 {...
7
by: Max | last post by:
I'm using late binding to automate to Outlook and I'm getting an ArgumentException when I create a delegate. The arguments I pass seem valid. This is my code: Type oType =...
4
by: CJ Taylor | last post by:
What does this mean? This method creates delegates for static methods only. An instance method is a method that is associated with an instance of a class; a static method is a method that is...
4
by: pamelafluente | last post by:
Hi, I am doing something like the following. MyDelegate is some delegate function I have defined and SomeMethodInfo is a function of type MyDelegate dim MethodToCall as MyDelegate ...
1
by: snibril | last post by:
Hi, I'm trying to delegate all events of a command button to a single method, handlesAll. I wrote the following code in VS.NET 2005, and it worked fine: public void setUpDelegates() { ...
10
by: pedrito | last post by:
I have a library I'm using that has a lapsed listener issue. I figured I'd just sneak in and do the unsubscription myself since I don't expect it to be fixed any time soon. So, I have the...
5
by: not_a_commie | last post by:
It seems that the only way to construct a struct from a type is to use Activator.CreateInstance. Is that true? Can anyone improve (performance-wise) upon this function below: /// <summary>...
10
by: Ron | last post by:
I have a situation where I have an object name as a string, and a method as a string. I need to construct a click handler with those two bits of information. This is what I came up with so far......
9
by: Klaudiusz Bryja | last post by:
Hi, I need Delegate.CreateDelegate method equivalent in compact framework. Best regards, Klaudiusz
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.