Around and About .NET World

Il blog di Marco Minerva
posts - 1671, comments - 2232, trackbacks - 2135

My Links

News

Contattami su Live Messenger:


MCTS: Windows, Web, Distributed Applications & SQL Server

MCPD: Enterprise Applications

Tag Cloud

Archives

Post Categories

Links

domenica 8 aprile 2007

Verificare se un tipo deriva da un altro

In diversi casi capita di dover verificare se un tipo deriva da un altro: l'esempio classico è la realizzazione di un sistema a plug-in. Il .NET Framework mette a disposizione diversi meccanismi per ottenere questo obiettivo, tutti contenuti nella classe System.Type. Tra le varie alternative, la soluzione più semplice consiste nell'utilizzo del metodo Type.IsAssignableFrom che, come si legga su MSDN:

[Returns] true if c and the current Type represent the same type, or if the current Type is in the inheritance hierarchy of c, or if the current Type is an interface that c implements, or if c is a generic type parameter and the current Type represents one of the constraints of c. false if none of these conditions are true, or if c is a null reference (Nothing in Visual Basic).

In altre parole, tale funzione permette di verificare sia se una classe deriva da un'altra, sia se essa implementa una certa interfaccia. Ad esempio:

public class Class1: IDisposable { //... } public class Class2: Class1 { //... } bool ret = typeof(IDisposable).IsAssignableFrom(typeof(Class1)); //true ret = typeof(Class1).IsAssignableFrom(typeof(Class2)); //true
Le ultime due istruzioni controllano, rispettivamente, se Class1 implementa l'interfaccia IDisposable e se Class2 deriva da Class1.

posted @ lunedì 1 gennaio 0001 00:00 | Feedback (2) | Filed Under [ C# ]

Auguri di Buona Pasqua!

posted @ lunedì 1 gennaio 0001 00:00 | Feedback (1) | Filed Under [ Windows Related ]

Powered by:
Powered By Subtext Powered By ASP.NET