noname wrote:
I'm learning C# generics recenly. How do i do to write the similar Java
function below in C#?
void printCollection(Collection<? extends A> c) {
for (Object e: c) {
System.out.println(e);
}}
In printCollection, I have to limit the bound of the argument, when is a
generic of Collection with some classes inherites from A. Does anyone
know
how I can do this in C#? Or if C# provides similar feature like widecards
in
Java?
There are no wildcards in C#. I'm not quite sure what the above code does,
exactly. Does it actually check, for the passed collection, that all
elements in the collection derive from A? In that case, there's no
equivalent in C#. Or does it filter the collection for elements that are
of type A? Also no equivalent. Or does it just let you assume that the
collection holds only A type elements? In that case, the foreach syntax
might do in C#:
public void PrintCollection(ArrayList list) {
// We don't really know what's going to be in list,
// but we assume all objects are deriving from A
foreach (A a in list)
// an exception will be thrown if an element shouldn't
// have the correct type
}
Usually, in C# you wouldn't do this kind of check in the parameter list of
a method. I can see how this mechanism might be handy, but it'll also be a
lot to do for the runtime (I'm assuming now that an actual check of some
kind is done on the collection passed in to the method). In C#, you'd use
a typed collection to begin with (List<A> comes to mind), so you can be
sure that it can only contain A type elements, no need to check that when
it's passed in somewhere. And for Generic classes you can also specify
constrainst for the types they are going to work with. Like this:
class MyClass<T> where T: A {
...
}
I'm not sure if this answers your question, though :-)
Oliver Sturm
--
omnibus ex nihilo ducendis sufficit unum
Spaces inserted to prevent google email destruction:
MSN oliver @ sturmnet.org Jabber sturm @ amessage.de
ICQ 27142619
http://www.sturmnet.org/blog