2013-04-28 36 views
13

我有一個抽象基類,我想實現一個方法來檢索繼承類的屬性屬性。事情是這樣的......如何從基類中獲得子類的`Type`

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

而且像這樣實現的...

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

過程與上面的代碼中GetCustomAttribute(),但不是一個可行的方法,因爲這不是一個具體的類。

爲了訪問繼承類,抽象類中的typeof(this)需要更改爲什麼?或者這不是一種好的做法,我應該在繼承類中完全實現該方法嗎?

+1

不應'用戶'繼承'MongoEntityBase'嗎? – 2013-04-28 15:03:18

+0

你是對的,謝謝。我修好了它 – bflemi3 2013-04-28 15:29:41

回答

13

您應該使用this.GetType()。這將爲您提供實際的實例的具體類型。

因此,在這種情況下:

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

注意,這樣它會返回最頂層級。也就是說,如果你有:

public class AdministrativeUser : User 
{ 

} 

public class User : MongoEntityBase 
{ 

} 

然後this.GetType()將返回AdministrativeUser


此外,這意味着,你可以實現的abstract基類之外的GetAttributeValue方法。您不需要實施者從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; 
    } 
} 

(也可以實現它作爲一個擴展方法,如果你想)

4

typeof(this)將無法​​編譯。

您正在搜索的是this.GetType()

相關問題