2009-10-05 14 views
31

मैं ऐसा करना चाहते हैं, लेकिन यह त्रुटि मिलती:.NET 2.0 में एक्सटेंशन विधियों का उपयोग करना?

Error 1 Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? [snipped some path stuff]

मैं कुछ जवाब यहां का कहना है कि देखा है, तो आप इस खुद के गुण को परिभाषित करने के लिए है।

मैं यह कैसे कर सकता हूं?

संपादित:

[AttributeUsage (AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)] 
public sealed class ExtensionAttribute : Attribute 
{ 
    public static int MeasureDisplayStringWidth (this Graphics graphics, string text) 
    { 

    } 
} 
+1

नहीं; आपको * दो * कक्षाओं की आवश्यकता है; विशेषता के लिए एक; विस्तार विधि के लिए एक; अपडेट करूंगी। –

उत्तर

58

की तरह तो:: यह है कि मैं क्या है

// you need this once (only), and it must be in this namespace 
namespace System.Runtime.CompilerServices 
{ 
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class 
     | AttributeTargets.Method)] 
    public sealed class ExtensionAttribute : Attribute {} 
} 
// you can have as many of these as you like, in any namespaces 
public static class MyExtensionMethods { 
    public static int MeasureDisplayStringWidth (
      this Graphics graphics, string text) 
    { 
      /* ... */ 
    } 
} 

वैकल्पिक रूप से; बस LINQBridge का संदर्भ जोड़ें।

+0

धन्यवाद मार्क, यह वास्तव में आपकी पोस्ट थी जिसे मैंने पढ़ा था। मैंने अभी कोशिश की लेकिन इसे मिला: त्रुटि एक्सटेंशन विधियों को गैर-जेनेरिक स्थैतिक वर्ग में परिभाषित किया जाना चाहिए, जहां मेरे पास इस तरह की विधि है: सार्वजनिक स्थैतिक int MeasureDisplayStringWidth (यह ग्राफिक्स ग्राफिक्स, ...) –

+0

इसके अलावा एक्सटेंशन एट्रिब्यूट कोई नाम हो, है ना? और विशेषता से विरासत क्यों? –

+3

आपको विशेषता के लिए विशेषता से प्राप्त करने की आवश्यकता है ... और इसे एक्सटेंशन एट्रिब्यूट कहा जाना चाहिए ताकि संकलक इसे ढूंढ सके। (यही वह उम्मीद है जिसे इसे बुलाया जा सकता है।) आपकी त्रुटि शायद यह है कि यह स्थिर वर्ग में नहीं है। –

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