无法将 GetTypes() 转换为接口
我正在扫描特定命名空间以查找实现接口的类型,并尝试将它们作为该接口而不只是类型返回,但我收到了 InvalidCastException
IEnumerable<IGameScript> GetDemos()
{
var results = Assembly.GetExecutingAssembly().GetTypes()
.Where(
x => x.IsClass
&& x.Namespace == "MMOClass.CodeBase.Demos"
&& x.Name.Contains("Demo")
&& x.GetInterfaces().Contains(typeof(IGameScript))
).Select(x => x);
return results.Cast<IGameScript>();
}
更新以响应 Reed 的回答:
IEnumerable<IGameScript> GetDemos()
{
var results = Assembly.GetExecutingAssembly().GetTypes()
.Where(
x => x.IsClass
&& x.Namespace == "MMOClass.CodeBase.Demos"
&& x.Name.Contains("Demo")
&& x.GetInterfaces().Contains(typeof(IGameScript))
).Select(x => Activator.CreateInstance(x) as IGameScript);
return results;
}
I'm scanning a particular namespace for types that implement an interface, and trying to return them as that interface rather than just Type, but i'm getting an InvalidCastException
IEnumerable<IGameScript> GetDemos()
{
var results = Assembly.GetExecutingAssembly().GetTypes()
.Where(
x => x.IsClass
&& x.Namespace == "MMOClass.CodeBase.Demos"
&& x.Name.Contains("Demo")
&& x.GetInterfaces().Contains(typeof(IGameScript))
).Select(x => x);
return results.Cast<IGameScript>();
}
Update in response to Reed's answer:
IEnumerable<IGameScript> GetDemos()
{
var results = Assembly.GetExecutingAssembly().GetTypes()
.Where(
x => x.IsClass
&& x.Namespace == "MMOClass.CodeBase.Demos"
&& x.Name.Contains("Demo")
&& x.GetInterfaces().Contains(typeof(IGameScript))
).Select(x => Activator.CreateInstance(x) as IGameScript);
return results;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的 LINQ 查询返回实现接口的类型 (
IEnumerable
) 集合,而不是该类型的对象集合。但是,您尝试返回一个
IEnumerable
,它是实现该接口的对象的实例列表。您需要构造实例才能转换为接口本身。Your LINQ query returns a collection of Types (
IEnumerable<System.Type>
) which implement the interface, not a collection of objects of that type.However, you're trying to return an
IEnumerable<IGameScript>
, which would be a list of instances of objects that implement that interface. You'll need to construct instances in order to cast to the interface itself.假设您有默认构造函数,您可以简单地将 Select LINQ 调用改造成类似这样的内容,并实际获取该类型的实例:
Assuming you have default constructors, you can simple reform your Select LINQ call to something like this and actually get the instances of that type: