[Kde-bindings] Using generics in Qyoto

Richard Dale richard.j.dale at gmail.com
Sat Jan 13 11:53:13 UTC 2007


On Friday 12 January 2007 23:40, Arno Rehn wrote:
> > No, I haven't done anything other than to find out about the List<T> type
> > in C#/mono. I was thinking we would:
> >
> > Change this C++
> > QList<QWidget *> associatedWidgets() const;
> >
> > to this C#
> > List<QWidget> associatedWidgets();
> >
> > I don't think we want a QList type in Qyoto. I'm assuming that the above
> > would't be a huge change to the code that currently marshalls from a
> > QList<QWidget *> to an ArrayList.
>
> Well, I thought about that and the difficulty is, that we have to create a
> List<T> at runtime from C++ where we don't know, what T is. The type of T
> is given to us as a string and exactly that is the problem. We can't just
> create a List<whatever> with 'new List<Type.GetType("whatever")'. The only
> possibility is via Reflection, and that way is, ahm, well, not very nice, I
> think. I've already tried it and it works, but as I said, not very nice to
> look at.
> I prefer the native List<T> of Mono, too, and would implement it via
> Reflection, if there's no other way.
>
> Here's what I tried: http://phpfi.com/193151
OK, interesting. I've been googling for stuff and I found this:

http://msdn2.microsoft.com/en-us/library/b8ytshk6.aspx

We can do what your code does in this way:

Type d1 = typeof(List<>);
Console.WriteLine("d1: " + d1);

Type[] typeArgs = {typeof(string)};
// Instead of 'typeof(string)', we could also a Qyoto class
// Type from its name for List<QWidget> etc

Type constructed = d1.MakeGenericType(typeArgs);
object o1 = Activator.CreateInstance(constructed);

Console.WriteLine("alist: " + o1);

List<string> list1 = (List<string>) o1; // cast
list1.Add("Hello World"); // add something
Console.WriteLine(list1[0]); // and print

Which is a bit less 'kludgy'. But I won't change any of the kalyptus code
generation for ArrayLists to List<>s until we're certain it's all
going to work though.

-- Richard



More information about the Kde-bindings mailing list