How can I set a Class Public Property as Type List<T>?
I want to define a public property in a User Control with a type of List that I can pass a List to and then have the control bind it to a repeater.
public partial class RepeaterPager :开发者_如何学JAVA System.Web.UI.UserControl
{
public List<T> DataSource;
}
The from calling code
List<someClass> list = new List<someClass>;
RepeaterPager1.DataSource = list ;
I thought this would be simple, but I am getting Error The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?) on the line that declares the public property. What am I doing wrong
Cheers
Stewart
This is only possible if the class containing property is generic. In theory, you could use generic method:
void SetDataSource<T>(List<T> dataSource)
but you'll lose type information elsewhere.
Maybe,
IEnumerable DataSource
will be a better option?
You can't have generic parameters in fields of a class with out the class being generic.
See this answer for info on making a usercontrol generic: C# generics usercontrol
Or you could just use a non-generic version, such as IEnumerable
or IList
.
You either need to define generic Type, or make RepeaterPager generic
public partial class RepeaterPager<T> : System.Web.UI.UserControl
{
public List<T> DataSource;
}
The general pattern for this type of data binding is to define DataSource as type object. Then, in the set method you can do a runtime check to verify the object is of a type you expect -- throw an exception or debug assert otherwise.
Besides, Repeater.DataSource is type object anyways ...
Many times I can get away without holding a reference to the datasource, so I pass it directly to the control:
public object DataSource
{
get { return myRepeater.DataSource; }
set {
if (value is IEnumerable) // or whatever your requirement is, if needed
myRepeater.DataSource = value;
else
throw new NotSupportedException("DataSource must be an IEnumerable type");
}
}
However, if you really do need to know about the type T, I would consider the following:
- If possible, use the generic class idea others have suggested.
- If you need to repeat this pattern for different classes, build a base class or Interface for all your data sources to derive from
- Use DataSource as type object, but just grab the type at run time using
obj.GetType()
. (Depending on your needs this may or may not work)
精彩评论