我有一个抽象基类,我想实现一个方法来检索继承类的属性属性。事情是这样的......如何从基类中获得子类的`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