472,986 Members | 3,164 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

RE: Invoking generic method with type constraint at runtime

"Anders Borum" wrote:
Hi

I need to invoke a generic method determined at runtime. The method has two
arguments, a string and a generic type that is constrained to a struct:

public void Add<T>(string key, T value) where T : struct

The method is an instance member located on a class called
CmsPropertyManager. I also have a number of other "Add" methods with
different overloads.

Usually, I find it quite easy to go by reflecting the type and bind to the
method, but this time it's been really hard to determine the correct binding
parameters. When I inspect the method info, I can see that the generic
argument is having a base type of System.ValueType. However, using this as
the binding signature doesn't yield any results.

// Acquire the method info (this is the part that I'm having trouble with)
MethodInfo methodInfo = typeof(CmsPropertyManager).GetMethod("Add", new
Type[] { typeof(string), typeof(System.ValueType) });

// Acquire the generic method info
MethodInfo genericInfo = methodInfo.MakeGenericMethod(type.Type);

// Invoke with a struct (represented by o)
genericInfo.Invoke(null, new object[] { this.uiKeyName.Value, o });

Please note that once I have the method / generic method info everything is
fine and dandy; that is, if I hardcode the methodinfo reference to the right
index in the reflected type (CmsPropertyManager) the rest of the reflection
part works perfectly).

Thanks in advance.

--
With regards
Anders Borum / SphereWorks
Microsoft Certified Professional (.NET MCP)
Hi Anders,

I'm afraid the GetMethod() does not currently support filtering on generic
parameters so you will have to loop through the existing methods using
GetMethods()

MethodInfo[] methods = t.GetMethods();
MethodInfo method = null;
foreach (MethodInfo mi in methods)
{
if (mi.Name == "Add"
&& mi.ContainsGenericParameters
&& mi.GetParameters().Length == 2
&& mi.GetParameters()[0].ParameterType == typeof(string)
&& mi.GetParameters()[1].ParameterType.IsGenericParameter)
{
method = mi;
break;
}
}

Or you could make a more generic method for it

public MethodInfo GetGenericMethod(Type t, string methodName, Type[]
parameters, int genericPosition)
{
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
if (!method.ContainsGenericParameters)
continue;

if (method.Name != methodName)
continue;

ParameterInfo[] parameterinfos = method.GetParameters();
if (parameterinfos.Length != parameterinfos.Length)
continue;

bool found = true;
for (int i = 0; i < parameterinfos.Length; i++)
{
if (i == genericPosition &&
!parameterinfos[i].ParameterType.IsGenericParameter)
{
found = false;
break;
}
if (i != genericPosition && parameterinfos[i].ParameterType !=
parameters[i])
{
found = false;
break;
}
}
if (found)
return method;
}
return null;
}

--
Happy Coding!
Morten Wennevik [C# MVP]
Oct 3 '08 #1
0 2265

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

Similar topics

17
by: Andreas Huber | last post by:
What follows is a discussion of my experience with .NET generics & the ..NET framework (as implemented in the Visual Studio 2005 Beta 1), which leads to questions as to why certain things are the...
6
by: Robert Zurer | last post by:
This method works but FxCop rightly complains "Generic methods should provide type parameter" http://www.gotdotnet.com/team/fxcop/docs/rules.aspx?version=1.32...
4
by: Jethro Guo | last post by:
C++ template use constraint by signature,It's very flexible to programmer but complex for complier, and at most time programmer can not get clear error message from complier if error occur. C#...
1
by: Lorraine | last post by:
Hi all, I have test application written in C# from which I am trying to dynamically invoke a DLL. I have two dll's the only difference being one is written in C# and the other in VB.NET. The test...
2
by: Brian Richards | last post by:
I'm trying to write a generic function (List<TPanelType> GetGenericPanels<TPanelType, TObjectType>()) that returns all UserControls that derive from T and and implement an interface...
9
by: mps | last post by:
I want to define a class that has a generic parameter that is itself a generic class. For example, if I have a generic IQueue<Tinterface, and class A wants to make use of a generic class that...
1
by: Suds | last post by:
Hi, I'm having an issue with invoking a Generic method that takes Generic Arguments. My method signature is public void GenericMethodWithGenericArguments<E, V>(List<EtheFirstList,...
9
by: Steve Richter | last post by:
in a generic class, can I code the class so that I can call a static method of the generic class T? In the ConvertFrom method of the generic TypeConvert class I want to write, I have a call to...
3
by: Anders Borum | last post by:
Hi I need to invoke a generic method determined at runtime. The method has two arguments, a string and a generic type that is constrained to a struct: public void Add<T>(string key, T value)...
0
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...
0
by: Aliciasmith | last post by:
In an age dominated by smartphones, having a mobile app for your business is no longer an option; it's a necessity. Whether you're a startup or an established enterprise, finding the right mobile app...
2
by: giovanniandrean | last post by:
The energy model is structured as follows and uses excel sheets to give input data: 1-Utility.py contains all the functions needed to calculate the variables and other minor things (mentions...
3
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be using a very simple database which has Form (clsForm) & Report (clsReport) classes that simply handle making the calling Form invisible until the Form, or all...
1
by: Teri B | last post by:
Hi, I have created a sub-form Roles. In my course form the user selects the roles assigned to the course. 0ne-to-many. One course many roles. Then I created a report based on the Course form and...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 1 Nov 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM) Please note that the UK and Europe revert to winter time on...
0
NeoPa
by: NeoPa | last post by:
Introduction For this article I'll be focusing on the Report (clsReport) class. This simply handles making the calling Form invisible until all of the Reports opened by it have been closed, when it...
0
isladogs
by: isladogs | last post by:
The next online meeting of the Access Europe User Group will be on Wednesday 6 Dec 2023 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, Mike...

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.