我有一个抽象基类,我想实现一个方法来检索继承类的属性属性。像这样......
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)
需要更改为什么?或者这不是一个好的做法,我应该在继承类中实现该方法吗?
答案 0 :(得分:14)
您应该使用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
。
此外,这意味着您可以在GetAttributeValue
基类之外实现abstract
方法。您不需要实施者继承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;
}
}
(如果您愿意,也可以将其作为扩展方法实现)
答案 1 :(得分:4)
typeof(this)
无法编译。
您要搜索的是this.GetType()
。