List<T> defined as member of class
I have a开发者_运维问答 list where i want the type to be definined by the call for example in the class i want something like
public class ClassName
{
public ListType<T> ListName { get; set; }
// other class items
}
and then the usage to be what sets the class type like
var className = new ClassName()
{
ListType<int> = data
};
so basically thats what i want, i have it working using dynamic so the class is
public class ClassName
{
public ListType<dynamic> ListName { get; set; }
// other class items
}
and the call is
var className = new ClassName()
{
ListType<dynamic> = data
};
this works but i would like to know if there is a better way to do this so i dont have to use dynamic
oh almost forgot to mention the ListType is
public class ListType<T> : List<T>
{
}
and so doesnt fail by having different types passed to it
thanks
edit: realised my usage of the code on stack overflow differed from my code
the ListType has a constructor that takes 3 arguments so the usage is more
var className = new ClassName()
{
ListName = new ListType<Type>(x, y, z)
}
How about
public class ClassName<T>
{
public ListType<T> ListName { get; set; }
// other class items
}
then use it like this:
var className = new ClassName<int>()
{
ListName = data;
};
Slight addition to Bertrand's answer gives you a way to not repeat the type argument in you specific use case, or even not mention it:
public static class ClassName
{
public static ClassName<T> Create<T>(ListType<T> list)
{
return new ClassName<T> { ListName = list };
}
public static ClassName<T> Create<T>(params T[] list)
{
return new ClassName<T> { ListName = new ListType<T>(list) };
}
}
Using the first method, you can write something like
ClassName.Create(new ListType<SomeType>(x, y, z));
using the second method, you can even write
ClassName.Create(x, y, z);
and let the compiler figure out that T
is SomeType
, but that doesn't work always.
Note that ClassName
is different class than ClassName<T>
and you might want to name it differently, e.g. ClassNameFactory
.
精彩评论