2013-04-28 40 views
13

我有一个抽象基类,我想实现一个方法来检索继承类的属性属性。事情是这样的......如何从基类中获得子类的`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)需要更改为什么?或者这不是一种好的做法,我应该在继承类中完全实现该方法吗?

+1

不应'用户'继承'MongoEntityBase'吗? – 2013-04-28 15:03:18

+0

你是对的,谢谢。我修好了它 – bflemi3 2013-04-28 15:29:41

回答

13

您应该使用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


此外,这意味着,你可以实现的abstract基类之外的GetAttributeValue方法。您不需要实施者从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; 
    } 
} 

(也可以实现它作为一个扩展方法,如果你想)

4

typeof(this)将无法​​编译。

您正在搜索的是this.GetType()

相关问题