G
Guest
Hi there
I have a question about generics in C# 2.0.
I have a generic class, Foo of T, which defines a field of type T. This
class is overridden in several base classes which define explicit types (say,
one does this with int, and another with string).
I now want to create a collection class to hold these Foo objects,
presumably inheriting from List<T>, which will be strongly typed. Inside the
collection, I want to define a new method which returns the type that the
field in the Foo is defined as.
I've written this as actual code below for clarity. The question I've got
is, how do I specify the return value of the method GetFirstValue so that it
is strongly typed - i.e. when the collection holds instances of IntFoo, this
method will return int; when the collection holds instances of StringFoo, it
will return string, and when it's holding Foo<T> it will return T?
Or does this particular scenario not make sense?
Thanks very much
- John
------------------
public abstract class Foo<T>
{
public T MyValue;
}
public class IntFoo : Foo<int>
{
}
public class StringFoo : Foo<string>
{
}
public class FooCollection<T> : List<T> where T : Foo<T>
{
// how can I specify the return value will be typeof(T.MyValue)?
public xxxxxxxx GetFirstValue()
{
return this[0].MyValue;
}
}
------------------
I have a question about generics in C# 2.0.
I have a generic class, Foo of T, which defines a field of type T. This
class is overridden in several base classes which define explicit types (say,
one does this with int, and another with string).
I now want to create a collection class to hold these Foo objects,
presumably inheriting from List<T>, which will be strongly typed. Inside the
collection, I want to define a new method which returns the type that the
field in the Foo is defined as.
I've written this as actual code below for clarity. The question I've got
is, how do I specify the return value of the method GetFirstValue so that it
is strongly typed - i.e. when the collection holds instances of IntFoo, this
method will return int; when the collection holds instances of StringFoo, it
will return string, and when it's holding Foo<T> it will return T?
Or does this particular scenario not make sense?
Thanks very much
- John
------------------
public abstract class Foo<T>
{
public T MyValue;
}
public class IntFoo : Foo<int>
{
}
public class StringFoo : Foo<string>
{
}
public class FooCollection<T> : List<T> where T : Foo<T>
{
// how can I specify the return value will be typeof(T.MyValue)?
public xxxxxxxx GetFirstValue()
{
return this[0].MyValue;
}
}
------------------