473,769 Members | 6,926 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating a type from a generic argument using Reflection?

Why can't I do this (it gives a syntactic error):?

foreach (System.Reflect ion.PropertyInf o oProp in
oObject.GetType ().GetPropertie s())
{
if ((oProp.Propert yType.IsGeneric Type) &&
(oProp.Property Type.GetGeneric TypeDefinition( ) ==
(typeof(IList<> ))))
{
Type oMyType = oProp.PropertyT ype.GetGenericA rguments()[0];

List<oMyTypeMyN ewVariable = new List<oMyType>() ;
}
}

Thanks in advance.

--
Nov 20 '06 #1
8 3201
3 problems; first: the compiler isn't going to believe you, in the same way
that it doesn't believe the following:

if(control is TextBox) {
TextBox tb = control;
}

second; you have checked IList<T>, and then assigned to List<T>.

third; oMyType is not a type; you can't use dynamic T in this way; you would
need to use reflection to create the generic type (or to invoke a generic
method typed to that type).

Marc
Nov 20 '06 #2
Marc Gravell escribió:
third; oMyType is not a type; you can't use dynamic T in this way; you would
need to use reflection to create the generic type (or to invoke a generic
method typed to that type).
How can I do it via Reflection then?

Thanks for your answer.

--
Nov 20 '06 #3
Full example:

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
TestGenerics(
new List<int>(),
new Collection<Cont rol>(),
new double[] {});
}
public static void TestGenerics(pa rams object[] values)
{
MethodInfo mi = typeof(Program) .GetMethod("Tes tGeneric");
foreach (object obj in values)
{
Type type = obj.GetType();
foreach (Type interfaceType in type.GetInterfa ces())
{
if (interfaceType. IsGenericType &&
interfaceType.G etGenericTypeDe finition()==typ eof(IList<>)) {
mi.MakeGenericM ethod(interface Type.GetGeneric Arguments()).In voke(null,
new object[] {obj});
break;
}

}
}
}
public static void TestGeneric<T>( IList<Titem)
{
Console.WriteLi ne("Made it: T=" + typeof(T).Name) ;
}
}
Nov 20 '06 #4
See my other post; I recommend the "branch to a generic method" approach, as
it means you only use reflection briefly to change to the second method;
this means that the code within the method *accessed* via reflection can be
fully compiled and optimised, and use generic syntax rather than reflection.
Note also that the inner-method would typically be private, so would require
a binding-flag; I only made it public to make it easy to obtain via
GetMethod().

Marc
Nov 20 '06 #5
Marc Gravell escribió:
Full example:

static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
public static void Main()
{
TestGenerics(
new List<int>(),
new Collection<Cont rol>(),
new double[] {});
}
public static void TestGenerics(pa rams object[] values)
{
MethodInfo mi = typeof(Program) .GetMethod("Tes tGeneric");
foreach (object obj in values)
{
Type type = obj.GetType();
foreach (Type interfaceType in type.GetInterfa ces())
{
if (interfaceType. IsGenericType &&
interfaceType.G etGenericTypeDe finition()==typ eof(IList<>)) {
mi.MakeGenericM ethod(interface Type.GetGeneric Arguments()).In voke(null,
new object[] {obj});
break;
}

}
}
}
public static void TestGeneric<T>( IList<Titem)
{
Console.WriteLi ne("Made it: T=" + typeof(T).Name) ;
}
}


Cool!!! I think that this is what I was looking for! I'll report soon.

Thanks very much.

--
Nov 20 '06 #6
Marc Gravell escribió:
See my other post; I recommend the "branch to a generic method" approach, as
it means you only use reflection briefly to change to the second method;
this means that the code within the method *accessed* via reflection can be
fully compiled and optimised, and use generic syntax rather than reflection.
Ok this solution finally works for me. Thanks very much.

Note also that the inner-method would typically be private, so would require
a binding-flag; I only made it public to make it easy to obtain via
GetMethod().
But I don't understand this, if I make the method private (which I think
it's the correct way) I can't access it with GetMethod, how can I do it?

Regards.

--
Nov 21 '06 #7
Ympostor escribió:
But I don't understand this, if I make the method private (which I think
it's the correct way) I can't access it with GetMethod, how can I do it?
Nevertheless, I have done it with:

BindingFlags.St atic | BindingFlags.No nPublic

However, isn't there a way to obtain the MethodInfo statically?
Something like this:

GetMethod(MyCla ss.MyStaticMeth od);

Thanks again.

--

Nov 21 '06 #8
If the method was non-generic (or we knew the T in advance), then you may be
able to do this by declaring a matching delegate signature, creating a
delegate pointing to the method, and then inspecting the delegate instance's
Method property (a MethodInfo).

However, AFAIK it is only possible to do this for concrete methods, and you
need to reference the generic method definition (not a closed implementation
there-of); so I don't know if it can be done (how, for instance, would you
declare the variable for this step?

There may be a non-delegate way of accessing the method, but given that we
are using reflection anyhow, an extra GetMethod isn't likely to be much of
an issue.

Marc
Nov 21 '06 #9

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

Similar topics

8
1364
by: Leszek Taratuta | last post by:
Hello, I have the following code: // Load the MenuBar.ascx user control. The control defines SavePropertyEvent event. UserControl ctrl = (UserControl)Page.LoadControl("~/MyApp/Controls/MenuBar.ascx"); // Get type information of the loaded user control.
4
5073
by: Ole Nielsby | last post by:
Here comes a generic class with a static property. Let's say they are exotic singleton pets. abstract class Pet {...} abstract class SharedPet<T>: Pet where T: SharedPet<T>, new() { private static T singleton = new T();
3
2829
by: john | last post by:
Hi to All To demonstrate: public class MyBaseGenericClass<T> { } public class MyGenericClass1<T: MyBaseGenericClass<T> {
9
12849
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
4859
by: Néstor Sánchez A. | last post by:
Hi, is there a way, maybe using reflection, to use a generic class passing the type parameter dynamicly (not kwnowing the exact type at compile time)? I tried the next example, but doesn't work: public abstract class Vehicle { ... } public class Aircraft : Vehicle { ... }
5
1588
by: Random | last post by:
How can I use reflection (or some other method) to find the type of an object that has been passed in to my method under an interface definition? I try to use GetType, but that won't work.
7
3807
by: colin | last post by:
Hi, I have my property editor wich uses the pop up collection editor for arrays etc, but i have had to use a generic wrapper for the elements in some types of collections. although the editing actually works well, and I can set the name ok in the primary property editor, this makes a mess of the type name displayed in the pop up colection editor, is there any way to change this ?
3
2264
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
2366
by: =?Utf-8?B?TW9ydGVuIFdlbm5ldmlrIFtDIyBNVlBd?= | last post by:
"Anders Borum" wrote: 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();
0
9589
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
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10049
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9997
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
9865
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
8873
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
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
5309
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3565
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.