我有一個抽象基類,我想實現一個方法來檢索繼承類的屬性屬性。事情是這樣的......如何從基類中獲得子類的`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)
需要更改爲什麼?或者這不是一種好的做法,我應該在繼承類中完全實現該方法嗎?
不應'用戶'繼承'MongoEntityBase'嗎? – 2013-04-28 15:03:18
你是對的,謝謝。我修好了它 – bflemi3 2013-04-28 15:29:41