如何从基类获取子类的`Type`

时间:2013-04-28 14:57:14

标签: c# reflection attributes

我有一个抽象基类,我想实现一个方法来检索继承类的属性属性。像这样......

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)需要更改为什么?或者这不是一个好的做法,我应该在继承类中实现该方法吗?

2 个答案:

答案 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()

相关问题