[英]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.我想在用户控件中定义一个公共属性,其类型为 List,我可以将 List 传递给该属性,然后让控件将其绑定到转发器。
public partial class RepeaterPager : 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.我认为这很简单,但在声明公共属性的行上出现错误找不到类型或命名空间名称“T”(您是否缺少 using 指令或程序集引用?)。 What am I doing wrong我究竟做错了什么
Cheers干杯
Stewart斯图尔特
This is only possible if the class containing property is generic.仅当包含属性的 class 是通用的时,这才有可能。 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.如果 class 是通用的,则不能在 class 的字段中使用通用参数。
See this answer for info on making a usercontrol generic: C# generics usercontrol有关使用户控件通用的信息,请参阅此答案: C# generics 用户控件
Or you could just use a non-generic version, such as IEnumerable
or IList
.或者您可以只使用非通用版本,例如IEnumerable
或IList
。
You either need to define generic Type, or make RepeaterPager generic您要么需要定义泛型类型,要么使 RepeaterPager 泛型
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.此类数据绑定的一般模式是将 DataSource 定义为类型 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.然后,在 set 方法中,您可以进行运行时检查以验证 object 是否属于您期望的类型——否则抛出异常或调试断言。
Besides, Repeater.DataSource is type object anyways...此外, Repeater.DataSource无论如何都是类型 object ......
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:但是,如果您确实需要了解类型 T,我会考虑以下内容:
obj.GetType()
.使用 DataSource 作为类型 object,但只需在运行时使用obj.GetType()
获取类型。 (Depending on your needs this may or may not work) (根据您的需要,这可能会或可能不会起作用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.