2009-02-18 13 views
12

परावर्तक मुझसे कहता है कि SortedList अपवाद के बजाय उदाहरण के लिए, उन्हें सीधे फेंकने की फेंकने के लिए एक ThrowHelper वर्ग का उपयोग करता है:सॉर्टेडलिस्ट कार्यान्वयन सीधे फेंकने के बजाय थ्रोहेल्पर का उपयोग क्यों करता है?

public TValue this[TKey key] 
{ 
    get 
    { 
     int index = this.IndexOfKey(key); 
     if (index >= 0) 
      return this.values[index]; 
     ThrowHelper.ThrowKeyNotFoundException(); 
     return default(TValue); 
    } 

जहां ThrowKeyNotFoundException बस से ज्यादा कुछ नहीं करता है:

throw new KeyNotFoundException(); 

नोट कैसे इस एक की आवश्यकता है डफ स्टेटमेंट "रिटर्न डिफॉल्ट (टीवीएयू)" जो पहुंच योग्य नहीं है। मुझे यह निष्कर्ष निकालना होगा कि यह एक पैटर्न है जो इसे उचित ठहराने के लिए पर्याप्त लाभ के साथ है।

ये लाभ क्या हैं?

+1

क्या आपने वास्तविक माइक्रोसॉफ्ट कोड देखा है और यह क्या संकलित नहीं है? –

+1

नहीं, मैंने नहीं किया है। क्या यह काफी अलग है? यदि ऐसा है, तो कृपया इसे एक उत्तर में समझाएं! :) –

उत्तर

19

ThrowHelper.cs स्रोत कोड के अनुसार मुख्य उद्देश्य जेट कोड कोड को कम करना है। नीचे लिंक से सीधी प्रतिलिपि पेस्ट है:

// This file defines an internal class used to throw exceptions in BCL code. 
// The main purpose is to reduce code size. 
// 
// The old way to throw an exception generates quite a lot IL code and assembly code. 
// Following is an example: 
//  C# source 
//   throw new ArgumentNullException("key", Environment.GetResourceString("ArgumentNull_Key")); 
//  IL code: 
//   IL_0003: ldstr  "key" 
//   IL_0008: ldstr  "ArgumentNull_Key" 
//   IL_000d: call  string System.Environment::GetResourceString(string) 
//   IL_0012: newobj  instance void System.ArgumentNullException::.ctor(string,string) 
//   IL_0017: throw 
// which is 21bytes in IL. 
// 
// So we want to get rid of the ldstr and call to Environment.GetResource in IL. 
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the 
// argument name and resource name in a small integer. The source code will be changed to 
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); 
// 
// The IL code will be 7 bytes. 
// IL_0008: ldc.i4.4 
// IL_0009: ldc.i4.4 
// IL_000a: call  void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) 
// IL_000f: ldarg.0 
// 
// This will also reduce the Jitted code size a lot. 
4

थ्रोहेल्पर क्या करता है इसे देखें। यह त्रुटि संदेशों के लिए संसाधन और सामान हो जाता है। इस विशेष उदाहरण में, कोई त्रुटि पाठ नहीं है, इसलिए ऐसा लगता है कि यह बेकार है, लेकिन उनके पैटर्न को शायद इसकी आवश्यकता है, इसलिए डेवलपर जिसने इसे लिखा है, उसे पैटर्न के रूप में देखना चाहिए।

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

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