2009-06-09 12 views
44

चलो कहते हैं कि हम इन दो वर्गों मिल गया है दो:सी # में बेस क्लास से, व्युत्पन्न प्रकार प्राप्त करें?

public class Derived : Base 
{ 
    public Derived(string s) 
     : base(s) 
    { } 
} 

public class Base 
{ 
    protected Base(string s) 
    { 

    } 
} 

मैं कैसे Base के निर्माता है कि Derived invoker है के भीतर से पता कर सकते हैं? यह क्या मैं के साथ आया है:

public class Derived : Base 
{ 
    public Derived(string s) 
     : base(typeof(Derived), s) 
    { } 
} 

public class Base 
{ 
    protected Base(Type type, string s) 
    { 

    } 
} 

वहाँ एक और तरीका typeof(Derived), Base के निर्माता के भीतर से प्रतिबिंब का उपयोग कर के किसी तरह से गुजर उदाहरण के लिए, की आवश्यकता नहीं है कि है?

उत्तर

79
using System; 
using System.Collections.Generic; 
using System.Text; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Base b = new Base(); 
      Derived1 d1 = new Derived1(); 
      Derived2 d2 = new Derived2(); 
      Base d3 = new Derived1(); 
      Base d4 = new Derived2(); 
      Console.ReadKey(true); 
     } 
    } 

    class Base 
    { 
     public Base() 
     { 
      Console.WriteLine("Base Constructor. Calling type: {0}", this.GetType().Name); 
     } 
    } 

    class Derived1 : Base { } 
    class Derived2 : Base { } 
} 

इस कार्यक्रम के निम्न आउटपुट:

Base Constructor: Calling type: Base 
Base Constructor: Calling type: Derived1 
Base Constructor: Calling type: Derived2 
Base Constructor: Calling type: Derived1 
Base Constructor: Calling type: Derived2 
+25

आप बहुत सारे कोड में एक दिलचस्प तथ्य छुपा रहे हैं। – VVS

+0

एक बेहतर उदाहरण 'व्युत्पन्न 1 डी 1 = नया बेस();' – Seph

+3

'व्युत्पन्न 1 डी 1 = नया बेस();' एक संकलित-समय त्रुटि उत्पन्न करता है, 'का आउटपुट दिखाने के लिए एक बेहतर उदाहरण होगा, आप शायद दूसरी तरफ का मतलब है। एफवाईआई '((बेस) नया व्युत्पन्न 1())। GetType()। नाम'" व्युत्पन्न 1 "है –

27

GetType() आप देना होगा कि आप क्या देख रहे हैं।

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