2013-04-28 14 views
13

Ho una classe base astratta in cui vorrei implementare un metodo che recuperi una proprietà attributo della classe ereditaria. Qualcosa di simile ...Come ottenere `Tipo` di sottoclasse dalla classe base

public abstract class MongoEntityBase : IMongoEntity { 

    public virtual object GetAttributeValue<T>(string propertyName) where T : Attribute { 
     var attribute = (T)typeof(this).GetCustomAttribute(typeof(T)); 
     return attribute != null ? attribute.GetType().GetProperty(propertyName).GetValue(attribute, null) : null; 
    } 
} 

e realizzato in questo modo ...

[MongoDatabaseName("robotdog")] 
[MongoCollectionName("users")] 
public class User : MonogoEntityBase { 
    public ObjectId Id { get; set; } 

    [Required] 
    [DataType(DataType.EmailAddress)] 
    public string email { get; set; } 

    [Required] 
    [DataType(DataType.Password)] 
    public string password { get; set; } 

    public IEnumerable<Movie> movies { get; set; } 
} 

Ma, naturalmente, con il codice di sopra del GetCustomAttribute() non è un metodo disponibile perché questa non è una classe concreta.

Cosa deve fare il typeof(this) nella classe astratta per poter accedere alla classe ereditaria? Oppure non è una buona pratica e dovrei implementare il metodo nella classe ereditaria?

+1

"Utente non ereditato da" MongoEntityBase'? –

+0

Hai ragione, grazie. L'ho riparato – bflemi3

risposta

13

È necessario utilizzare this.GetType(). Questo ti fornirà il effettivo tipo concreto dell'istanza.

Quindi in questo caso:

public virtual object GetAttributeValue<T>(string propertyName) where T : Attribute { 
    var attribute = this.GetType().GetCustomAttribute(typeof(T)); 
    return attribute != null ? attribute.GetType().GetProperty(propertyName).GetValue(attribute, null) : null; 
} 

Nota, che restituisca la parte superiore più di classe. Cioè, se si ha:

public class AdministrativeUser : User 
{ 

} 

public class User : MongoEntityBase 
{ 

} 

Poi this.GetType() tornerà AdministrativeUser.


Inoltre, questo significa che è possibile implementare il metodo GetAttributeValue al di fuori della classe abstract base. Non è necessario che gli implementatori ereditino da MongoEntityBase.

public static class MongoEntityHelper 
{ 
    public static object GetAttributeValue<T>(IMongoEntity entity, string propertyName) where T : Attribute 
    { 
     var attribute = (T)entity.GetType().GetCustomAttribute(typeof(T)); 
     return attribute != null ? attribute.GetType().GetProperty(propertyName).GetValue(attribute, null) : null; 
    } 
} 

(potrebbe anche implementare come un metodo di estensione, se si desidera)

4

typeof(this) non verrà compilato.

Quello che stai cercando è this.GetType().

Problemi correlati