2013-04-28 10 views
13

से उप-वर्ग का 'टाइप` कैसे प्राप्त करें मेरे पास एक सार आधार वर्ग है जहां मैं एक ऐसी विधि को कार्यान्वित करना चाहता हूं जो विरासत वर्ग की विशेषता गुण पुनर्प्राप्त करे। कुछ इस तरह ...बेस क्लास

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

'मोंगोइन्टिटीबेस' से 'उपयोगकर्ता' का उत्तराधिकारी नहीं होना चाहिए? –

+0

आप सही हैं, धन्यवाद। मैंने ठीक कर दिया – bflemi3

उत्तर

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() है।