Ответ 1
Вы должны использовать 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;
}
}
(может также реализовать его как метод расширения, если вы хотите)