473,396 Members | 2,013 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,396 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 2314

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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
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
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.