|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
[Reflection] best way to know if a Type implements an interfaceSuppose I have an interface IPlugin, and a Type myType.
What's the best way to ask myType if it implements the IPlugin interface? I came out with this, but I don't know if there are better alternatives: bool implementsIPlugin = typeof(IPlugin).IsAssignableFrom(myType); Voivod <francesco.pi***@gmail.com> wrote:
> Suppose I have an interface IPlugin, and a Type myType. Seems like a very good way to me. I can't remember off-hand whether it > > What's the best way to ask myType if it implements the IPlugin > interface? > > I came out with this, but I don't know if there are better > alternatives: > bool implementsIPlugin = typeof(IPlugin).IsAssignableFrom(myType); will return true if myType is an interface deriving from IPlugin though - one to check. -- Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet If replying to the group, please do not mail me too On May 12, 11:52 pm, Jon Skeet [C# MVP] <s***@pobox.com> wrote:
Show quote > Voivod <francesco.pi***@gmail.com> wrote: if (myType is IPlugin)> > Suppose I have an interface IPlugin, and a Type myType. > > > What's the best way to ask myType if it implements the IPlugin > > interface? > > > I came out with this, but I don't know if there are better > > alternatives: > > bool implementsIPlugin = typeof(IPlugin).IsAssignableFrom(myType); > > Seems like a very good way to me. I can't remember off-hand whether it > will return true if myType is an interface deriving from IPlugin though > - one to check. > > -- > Jon Skeet - <s***@pobox.comhttp://www.pobox.com/~skeet Blog:http://www.msmvps.com/jon.skeet > If replying to the group, please do not mail me too { IPlugin myPlugin = (IPlugin)myType; // do stuff } // or IPlugin myPlugin = myType as IPlugin; if (myPlugin!=null) { // do stuff } |
|||||||||||||||||||||||