473,725 Members | 2,419 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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
CmsPropertyMana ger. 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.ValueTyp e. 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(CmsPrope rtyManager).Get Method("Add", new
Type[] { typeof(string), typeof(System.V alueType) });

// Acquire the generic method info
MethodInfo genericInfo = methodInfo.Make GenericMethod(t ype.Type);

// Invoke with a struct (represented by o)
genericInfo.Inv oke(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 (CmsPropertyMan ager) 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.ContainsGene ricParameters
&& mi.GetParameter s().Length == 2
&& mi.GetParameter s()[0].ParameterType == typeof(string)
&& mi.GetParameter s()[1].ParameterType. IsGenericParame ter)
{
method = mi;
break;
}
}

Or you could make a more generic method for it

public MethodInfo GetGenericMetho d(Type t, string methodName, Type[]
parameters, int genericPosition )
{
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
if (!method.Contai nsGenericParame ters)
continue;

if (method.Name != methodName)
continue;

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

bool found = true;
for (int i = 0; i < parameterinfos. Length; i++)
{
if (i == genericPosition &&
!parameterinfos[i].ParameterType. IsGenericParame ter)
{
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 2364

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

Similar topics

17
3320
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 way they are. ***** Summary & Questions ***** In a nutshell, the current .NET generics & .NET framework make it sometimes difficult or even impossible to write truly generic code. For example, it seems to be impossible to write a truly generic
6
2075
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 &url=/Design/GenericMethodsShouldProvideTypeParameter.html public sealed class ReflectionAgent { public static T GetCustomAttribute<T>(MemberInfo memberInfo)
4
2046
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# generic use constraint by type,complier is relaxed, but it is very limited to programmer.Is there a way to get merits of both? Maybe the following way can achieve this purpose : //First add a keyword "constrant" to modify class or struct just...
1
1877
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 application is able to sucessfully invoke the dll written in C#. However when attempting to invoke the VB.NET version of the dll the following error message occurs: Unhandled Exception: System.ArgumentNullException: Value cannot be null....
2
2662
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 IGenericPropertyPanel<V> such that U implements or derives from V. The idea being that I can discover (via reflection) all the controls that display or allow editing of an object properties, it's base classes and interfaces. Then I can put them in some kind of...
9
12844
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 implements IQueue<Tfor all types T (so it can make use of queues of various object types internally). As useful as this is, it doesn't seem possible. The natural (but illegal) notation would be something like class A<QueueClasswhere QueueClass :...
1
2783
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, List<VtheSecondList); I pass the name of the method, the arguments for the "GenericMethodWithGenericArguments" to another method, which is supposed to invoke this method using the Invoke method in the MethodInfo class. My process of invocation is as follows
9
5849
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 the static Parse method of the conversion class. if (InValue is string) return T.Parse((string)InValue); else return base.ConvertFrom(context, culture, InValue);
3
2263
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) 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.
0
8874
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9393
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9164
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9092
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6000
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4775
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3212
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2622
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2151
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.