Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
抽象类型作为方法(.net,c#)中的参数_C#_.net_Generics - Fatal编程技术网

抽象类型作为方法(.net,c#)中的参数

抽象类型作为方法(.net,c#)中的参数,c#,.net,generics,C#,.net,Generics,我使用以下方法填充DropDownList控件 protected void LoadDropDownList(DropDownList ddl, IEnumerable<A> source) { ddl.DataSource = source; ddl.DataBind(); } 受保护的void LoadDropDownList(DropDownList ddl,IEnumerable源) { ddl.DataSource=源; ddl.DataBind();

我使用以下方法填充DropDownList控件

protected void LoadDropDownList(DropDownList ddl, IEnumerable<A> source)
{
    ddl.DataSource = source;
    ddl.DataBind();
}
受保护的void LoadDropDownList(DropDownList ddl,IEnumerable源)
{
ddl.DataSource=源;
ddl.DataBind();
}
我的问题是,我是否可以使该方法更抽象,以便它也可以接受类型B的IEnumerable?

受保护的void LoadDropDownList(DropDownList ddl,IEnumerable source){
protected void LoadDropDownList<T>(DropDownList ddl, IEnumerable<T> source) { 
    ...
...

请参阅。

什么是类型B?另外,如果您可以提供整个classIt也会很有帮助。坚持类型
T
派生自某个具有
DataSource
属性和名为
DataBind()的方法的超类也可能是一个好主意
。是的,我想提一下。这不是必需的,但是如果您要编写可以将任何内容加载到列表中的代码,它们必须实现一些公共基类。您可以在
之后和
{
之前添加
,其中T:SomeBaseClass
。谢谢!为什么LoadDropDownList(DropDownList ddl,IEnumerable源)不起作用?因为这表示您需要一个可以枚举
T
s的
IEnumerable
,其中
T
是一个类。您需要在参数列表之前添加
,以指示
T
是一个类型参数。有关详细信息,请参阅我在回答中提供的链接。换句话说,完全删除强类型?:/
protected void LoadDropDownList(DropDownList ddl, IEnumerable source) {
     ddl.DataSource = source;
     ddl.DataBind();
}