How to create a list of shared delegate instances?

I want to create a collection of factory methods that can instantiate various objects whose type will be known only at runtime. I can easily create a delegate for this:

delegate T InstanceCreator<T>() 

but this gives a compiler error: "cannot resolve T character"

 Dictionary<string, InstanceCreator<T>> 

so instead i just declare

 Dictionary<string, Delegate> 

I tried to fill this lack of type specificity in the Add method, but ran into the same problem.

 public void AddFactory(string typeName, InstanceCreator<T> factory) 

Is there a better way to make sure that only InstanceCreator<T> delegates are added to the collection?

+4
source share
7 answers

You can make AddFactory a universal method:

 public void AddFactory<T>(string typeName, InstanceCreator<T> factory) 

This will limit it to adding InstanceCreator<T> elements.

+1
source
 public void AddFactory(string typeName,InstanceCreator<T> factory) 

Where is T ? To do this, you need to make a general method for this:

 public void AddFactory<T>(string typeName,InstanceCreator<T> factory) 
+1
source

Make the AddFactory general method:

 public void AddFactory<T>(string typeName, InstanceCreator<T> factory) 
0
source

try like this ....

 public void AddFactory<T>(string typeName,InstanceCreator<T> factory) 
0
source

You need to pass the generic parameter type through a class or method.

I would suggest using the standard Func <TResult> generic delegate:

Generic class type parameter:

 public class FactoryRepository<T> { IDictionary<string, Func<T>> factoryCache; public FactoryRepository() { this.factoryCache = new Dictionary<string, Func<T>>(); } public void AddFactory(string key, Func<T> factory) { this.factoryCache.Add(key, factory); } } 

The parameter of the general type of method:

 public void AddFactory<T>(string key, Func<T> factory) { // IDictionary<string, Func<T>> factoryCache factoryCache.Add(key, factory); } 
0
source

In what area do you declare the delegate.

 delegate T InstanceCreator<T>() 

If at the level of the namespace T you sue him, and T, which you use in your method, do not match. Declare the delegate within the class and it should work.

0
source

If you do not need to have typeName as a string, I would suggest having Dictionary<Type, Delegate> and use it something like this:

 Dictionary<Type, Delegate> factories = new Dictionary<Type, Delegate>(); public void AddFactory<T>(InstanceCreator<T> factory) { factories.Add(typeof(T), factory); } public InstanceCreator<T> GetFactory() { return (InstanceCreator<T>)factories[typeof(T)]; } 

In addition, there is no need to create your own delegate types, Func<T> will work just as well.

0
source

Source: https://habr.com/ru/post/1381389/


All Articles