Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/azure/12.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
Generics 使用where T:Interface的泛型扩展方法_Generics_C# 4.0_Extension Methods - Fatal编程技术网

Generics 使用where T:Interface的泛型扩展方法

Generics 使用where T:Interface的泛型扩展方法,generics,c#-4.0,extension-methods,Generics,C# 4.0,Extension Methods,这两种扩展方法是否相同,或者使用其中的一种是否存在危险 public static T GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface { //do somthing that returns an item of T } public static T GetSomthingFromListOf(此列表),其中T:IMyInterface { //执行返回T项的操作 } 对

这两种扩展方法是否相同,或者使用其中的一种是否存在危险

public static T  GetSomthingFromListOf<T>(this List<T> list)where T: IMyInterface
{
    //do somthing that returns an item of T
}
public static T GetSomthingFromListOf(此列表),其中T:IMyInterface
{
//执行返回T项的操作
}

public static IMyInterface GetSomthingFromList(this List<IMyInterface> list)
{
    //do somthing that returns an item of IMyInterface
}
public静态IMyInterface GetSomthingFromList(此列表)
{
//执行返回IMyInterface项的操作
}

唯一真正的区别在于返回类型,第一个将返回类型本身并约束它,以便它必须实现
IMyInterface
,第二个将只返回
IMyInterface
实例


当您只想公开接口的成员时,第二种方法非常有用;第一种方法适用于需要返回原始类型的情况,但请确保在方法中将其视为@Clint answer之外的
IMyInterface

1) 如果您有
列表的实例
,则只有通用扩展方法可用


2) 如果您将
struct
作为参数传递给非泛型方法,该方法期望发生接口装箱

这一点解释得很好,但没有考虑到在第二个实现中我只能使用接口成员这一事实。在第一个示例中,我可以使用所有成员,但它只需要是IMyInterface类型。所以我的问题需要第一个:)@Clint:如果
T
是一个结构呢?@apocapse我从来都不需要一个带接口的结构,但是如果它是一个结构,会有什么问题呢?@apocapse我不太清楚,但它仍然应该以同样的方式工作,因为结构可以实现接口,但不能从基类派生。