C# 返回IQueryable<;T>;从泛型方法
因此,我有以下代码:C# 返回IQueryable<;T>;从泛型方法,c#,generics,iqueryable,C#,Generics,Iqueryable,因此,我有以下代码: private readonly Dictionary<string, IGame> _gameLookup = new Dictionary<string, IGame>(); public T LookupGame<T>(string name) where T : IGame { if (name == null) throw new ArgumentNullException("name"
private readonly Dictionary<string, IGame> _gameLookup = new Dictionary<string, IGame>();
public T LookupGame<T>(string name) where T : IGame
{
if (name == null) throw new ArgumentNullException("name");
Type t = typeof(T);
if (_gameLookup.Any(d => d.Key == name))
{
return (T)_gameLookup[name];
}
var newInstance = (T)AppDomain.CurrentDomain.GetUnityContainer().Resolve(t, name);
if (newInstance != null)
{
_gameLookup.Add(name, newInstance);
return newInstance;
}
return default(T);
}
public IQueryable<T> ListGames<T>() where T : IGame
{
var games = _gameLookup.Where(d => d.GetType() == typeof (T));
return (IQueryable<T>) games;
}
private readonly Dictionary\u gameLookup=new Dictionary();
公共T LookupGame(字符串名称),其中T:IGame
{
如果(name==null)抛出新的ArgumentNullException(“name”);
类型t=类型(t);
if(_gameLookup.Any(d=>d.Key==name))
{
返回(T)_gameLookup[名称];
}
var newInstance=(T)AppDomain.CurrentDomain.GetUnityContainer().Resolve(T,名称);
if(newInstance!=null)
{
_gameLookup.Add(名称,newInstance);
返回newInstance;
}
返回默认值(T);
}
公共IQueryable ListGames()其中T:IGame
{
var games=_gameLookup.Where(d=>d.GetType()==typeof(T));
返回(IQueryable)游戏;
}
我的问题是ListGames方法。(LookupGame方法只是在我正在做的事情中包含了一些上下文。)
我一辈子都搞不懂如何操纵事物以获得一个理想的结果。我尝试了很多方法,包括.AsQueryable()方法、强制转换各种方法等等
如果能洞悉我的错误,我们将不胜感激 结果类型是
IEnumerable
,您无法将其转换为IQueryable
(无论如何,不是通过简单的转换)
您可以尝试AsQueryable()
:
结果类型是
IEnumerable
,您无法将其强制转换为IQueryable
(无论如何,不是通过简单的强制转换)
您可以尝试AsQueryable()
:
您的代码中存在多个问题:
KeyValuePair
上调用GetType
,(因为\u gameLookup
是一个字典,所以实现了IEnumerable
它是d
的类型),但显然您希望在值上使用它games
)的类型为IEnumerable
,因此需要删除KeyValuePair
部分public IQueryable<T> ListGames<T>() where T : IGame
{
return _gameLookup.Values
.OfType<T>()
.AsQueryable();
}
public IQueryable ListGames()其中T:IGame
{
返回_gameLookup.Values
第()类
.AsQueryable();
}
您的代码中存在多个问题:
KeyValuePair
上调用GetType
,(因为\u gameLookup
是一个字典,所以实现了IEnumerable
它是d
的类型),但显然您希望在值上使用它games
)的类型为IEnumerable
,因此需要删除KeyValuePair
部分public IQueryable<T> ListGames<T>() where T : IGame
{
return _gameLookup.Values
.OfType<T>()
.AsQueryable();
}
public IQueryable ListGames()其中T:IGame
{
返回_gameLookup.Values
第()类
.AsQueryable();
}
为什么需要IQueryable而不是IEnumerable?为什么需要IQueryable而不是IEnumerable?啊。。。森林穿过树林。感谢您的快速响应。MSDN上列出的唯一版本的AsQueryable
采用IEnumerable
,但Values
仅实现IEnumerable
,因此它不会发现带有错误的重载,例如无法从“System.Collections.Generic.Dictionary.ValueCollection”转换为“System.Collections.Generic.IEnumerable”
Ah。。。森林穿过树林。感谢您的快速响应。MSDN上列出的唯一版本的AsQueryable
采用IEnumerable
,但Values
仅实现IEnumerable
,因此它不会发现带有错误的重载,例如无法从“System.Collections.Generic.Dictionary.ValueCollection”转换为“System.Collections.Generic.IEnumerable”