साथ एक सामान्य विधि कॉलिंग कहते हैं कि मैं निम्नलिखित वर्गोंएक गतिशील प्रकार
public class Animal { .... }
public class Duck : Animal { ... }
public class Cow : Animal { ... }
public class Creator
{
public List<T> CreateAnimals<T>(int numAnimals)
{
Type type = typeof(T);
List<T> returnList = new List<T>();
//Use reflection to populate list and return
}
}
अब कुछ कोड में बाद में मैं क्या पशु बनाने के लिए पढ़ने के लिए करना चाहते हैं देता है।
Creator creator = new Creator();
string animalType = //read from a file what animal (duck, cow) to create
Type type = Type.GetType(animalType);
List<animalType> animals = creator.CreateAnimals<type>(5);
अब समस्या यह है कि अंतिम पंक्ति मान्य नहीं है। क्या ऐसा करने के लिए कुछ शानदार तरीका है?
जेनिक्स वास्तव में यहां जाने का तरीका नहीं है, आपको केवल सूची सूची बनाना चाहिए और व्युत्पन्न कक्षाएं बनाने के लिए एक्टिवेटर का उपयोग करना चाहिए। –
Doggett