C# 返回与泛型中的输入类型相同的实例类型
已尝试此代码:C# 返回与泛型中的输入类型相同的实例类型,c#,linq,ienumerable,C#,Linq,Ienumerable,已尝试此代码: public static T NotEmpty<T, X> (T instance, string paramName = null) where T : IEnumerable<X> { if (instance != null) if (instance.Any ()) return instance; throw new Exception (); } static void Main (
public static T NotEmpty<T, X> (T instance, string paramName = null) where T : IEnumerable<X>
{
if (instance != null)
if (instance.Any ())
return instance;
throw new Exception ();
}
static void Main (string[] args)
{
var list = new List<int> () { 1, 2, 3 };
var t = NotEmpty (list);
}
public static T NotEmpty(T实例,字符串paramName=null),其中T:IEnumerable
{
if(实例!=null)
if(instance.Any())
返回实例;
抛出新异常();
}
静态void Main(字符串[]参数)
{
var list=newlist(){1,2,3};
var t=NotEmpty(列表);
}
编辑:
所以我想传递实现IEnumerable
的任何类型,比如List
,并返回相同类型的实例(List
)
错误:var t=NotEmpty(列表)代码>
无法从用法推断方法NoName.Program.NotEmpty(T,string)
的类型参数。尝试显式指定类型参数
我相信你不需要两个通用参数。您可以将T
替换为IEnumerable
public静态IEnumerable NotEmpty(IEnumerable实例,字符串paramName=null)
{
if(instance!=null&&instance.Any())
返回实例;
抛出新异常();
}
编译器在哪个位置说这个?
public static IEnumerable<T> NotEmpty<T> (IEnumerable<T> instance, string paramName = null)
{
if (instance != null && instance.Any())
return instance;
throw new Exception ();
}