2011-01-09 24 views
14

मैं कैसे समझ सामान्य की कमी से काम के साथ एक समस्या है। मुझे लगता है कि मुझे यहां कुछ महत्वपूर्ण याद आ रहा है। मैंने टिप्पणियों में अपने प्रश्न संलग्न किए हैं और कुछ स्पष्टीकरण प्रदान करने के लिए आभारी होंगे।टी पर जेनेरिक बाधा संदर्भ प्रकार और मूल्य प्रकार के साथ-साथ?

//1st example: 

class C <T, U> 
    where T : class 
    where U : struct, T 
{ 
} 
//Above code compiles well, 
//On first sight it looks like U might be reference type and value type 
//at the same time. The only reason I can think of, is that T may be an 
//interface which struct can implement, Am I correct? 

//2nd example 

class CC<T, U> 
    where T : class, new() 
    where U : struct, T 
{ 
} 

//I added also a reguirement for parameterless constructor 
//and, much to my surprise, it still compiles what is 
//a bit inexplicable for me. 
//What 'U' would meet the requirement to be 
//value type, reference type and have a contructor at the same time? 

उत्तर

12

इसमें कुछ भी गलत नहीं है। के constraints on the type parameters की परिभाषा पर नजर डालते हैं:

  • T : class - प्रकार तर्क टी, एक संदर्भ प्रकार होना चाहिए किसी भी वर्ग, इंटरफ़ेस, प्रतिनिधि, या सरणी प्रकार भी शामिल है।
  • U : struct - प्रकार तर्क यू एक मूल्य के प्रकार होना चाहिए।
  • U : T - प्रकार तर्क यू है या वर्ग टी

से निकाले जाते हैं चाहिए तो तुम सब करने की जरूरत है एक मान प्रकार है कि एक संदर्भ प्रकार से निकला है लगता है। सबसे पहले कि असंभव लग सकता है, लेकिन अगर आपको लगता है थोड़ा मुश्किल आपको याद होगा कि सभी structs वर्ग object से निकाले जाते हैं, तो यह दोनों अपने उदाहरण के लिए ठीक काम करता है:

new C<object, int>(); 

लेकिन यदि आप struct और class स्वैप तो यह संकलित नहीं होगा:

// Error - Type parameter 'T' has the 'struct' constraint so 'T' 
//   cannot be used as a constraint for 'U' 
class C<T, U> 
    where T : struct 
    where U : class, T 
{ 
} 
+1

हां? तथा ? आपने इसे टी के लिए निर्दिष्ट किया है, जो ऑब्जेक्ट कन्स्ट्रक्टर से मेल खाता है। ठीक है। –

+0

हाँ आप सही हैं, मैंने इसे गलत पढ़ा है। @ मार्क बार्स आपने कहा था कि सभी structs 'ऑब्जेक्ट' से प्राप्त होते हैं। यदि ऐसा है तो मैं 'वर्ग सीएस जहां टी था: वर्ग {}' कोड 'सीएस obj = नए सीएस () की तरह,' जबकि कार्य नहीं करेगा 'DateTime' आपत्ति उठाने castable है। – nan

+0

@Andrzej Nosal: हाँ, क्योंकि बाधा 't: class' मतलब यह नहीं है * टी आपत्ति उठाने castable है *। इसका मतलब है * टी एक संदर्भ प्रकार होना चाहिए *। डेटटाइम एक संदर्भ प्रकार नहीं है। –

संबंधित मुद्दे