2013-04-28 32 views
13

Kalıtım sınıfının öznitelik özelliğini alacak bir yöntem uygulamak istediğim soyut bir taban sınıfım var. Böyle bir şey ...Alt sınıfın alt sınıfından "Tür" alt sınıfı nasıl elde edilir

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; 
    } 
} 

Ve şöyle Uygulanan ... Bu bir beton sınıfı olmadığı için

[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; } 
} 

Fakat yukarıdaki kodu GetCustomAttribute() ile tabii

kullanılabilir bir yöntem değildir.

Soyut sınıftaki typeof(this), miras sınıfına erişebilmek için ne olmalıdır? Veya bu iyi bir uygulama değil mi ve miras sınıfındaki yöntemi tamamen mi uygulamalıyım?

+1

Kullanıcı 'MongoEntityBase'den miras almamalıdır? –

+0

Haklısın, teşekkürler. Onardım – bflemi3

cevap

13

this.GetType() kullanmalısınız. Bu, örneğin gerçek beton türünü sağlayacaktır. Yani bu durumda

:

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; 
} 

Not, bu en üstteki sınıf döneceğini.

public class AdministrativeUser : User 
{ 

} 

public class User : MongoEntityBase 
{ 

} 

Sonra this.GetType()AdministrativeUser döndürür: Eğer olsaydı bu vardır.


Ayrıca, bu abstract temel sınıf dışında GetAttributeValue yöntemini uygulamak anlamına gelir. Uygulayıcıların MongoEntityBase'dan miras almasını istemezsiniz.

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; 
    } 
} 

(sen isterseniz de bir uzantısı yöntemi olarak uygulamak olabilir)

4

typeof(this) derlemek olmaz.

Ne aradığınız this.GetType().

İlgili konular