473,396 Members | 2,109 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.

Creating a type from a generic argument using Reflection?

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

foreach (System.Reflection.PropertyInfo oProp in
oObject.GetType().GetProperties())
{
if ((oProp.PropertyType.IsGenericType) &&
(oProp.PropertyType.GetGenericTypeDefinition() ==
(typeof(IList<>))))
{
Type oMyType = oProp.PropertyType.GetGenericArguments()[0];

List<oMyTypeMyNewVariable = new List<oMyType>();
}
}

Thanks in advance.

--
Nov 20 '06 #1
8 3170
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<Control>(),
new double[] {});
}
public static void TestGenerics(params object[] values)
{
MethodInfo mi = typeof(Program).GetMethod("TestGeneric");
foreach (object obj in values)
{
Type type = obj.GetType();
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()==typeof(I List<>)) {
mi.MakeGenericMethod(interfaceType.GetGenericArgum ents()).Invoke(null,
new object[] {obj});
break;
}

}
}
}
public static void TestGeneric<T>(IList<Titem)
{
Console.WriteLine("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<Control>(),
new double[] {});
}
public static void TestGenerics(params object[] values)
{
MethodInfo mi = typeof(Program).GetMethod("TestGeneric");
foreach (object obj in values)
{
Type type = obj.GetType();
foreach (Type interfaceType in type.GetInterfaces())
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition()==typeof(I List<>)) {
mi.MakeGenericMethod(interfaceType.GetGenericArgum ents()).Invoke(null,
new object[] {obj});
break;
}

}
}
}
public static void TestGeneric<T>(IList<Titem)
{
Console.WriteLine("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.Static | BindingFlags.NonPublic

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

GetMethod(MyClass.MyStaticMethod);

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
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 =...
4
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() {...
3
by: john | last post by:
Hi to All To demonstrate: public class MyBaseGenericClass<T> { } public class MyGenericClass1<T: MyBaseGenericClass<T> {
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: 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: ...
5
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
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...
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: =?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...
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: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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?
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,...
0
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...
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...

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.