简体   繁体   中英

Generic function with different classes (with parameters)?

My magic syntax would look like this:

public List<T> LoadItems(string fileName) where T : new (Dictionary<string,string>)
{
   ...
   List<T> List = new List<T>();
   while(reader.peek() != -1)
   {  
       Dictionary<string, string> NameValuePairs = new Dictionary<string,string>();
       ...
       //parse file and load dictionary with name value pairs
       ...
       List.Add(new T(NameValuePairs));

   }
} 

I would then like to be able to call this function like this...

public List<Class1> LoadClass1()
{
    return LoadItems<Class1>("file1.csv");
}

public List<Class2> LoadClass1()
{
    return LoadItems<Class2>("file2.csv");
}

public LisT<Class3> LoadClass1()
{
    return LoadItems<Class3>("file3.csv");
}

I realize that this can't be done like this, but is there a way to implement something that works like this, perhaps using an interface for my three classes?

If your classes, Class1, Class2, Class3, all take a dictionary as a constructor parameter, you could have them inherit from a common base class and use Activator.CreateInstance(typeof(T), NameValuePairs) to create instances of your classes.

If you go that route, you'll want to make your generic constraint where T : BaseClass and do some error checking/exception handling around your type creation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM