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 == "MMOCl开发者_运维问答ass.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;
}
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.
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:
.Select(x => Activator.CreateInstance(x))
精彩评论