M
M
mletov2018-04-05 15:20:14
OOP
mletov, 2018-04-05 15:20:14

Is it possible to create a dictionary of delegates returning a List?

Please tell me:
There is a generic class There is a delegate in it And there is a dictionary
class MyClass<T> where T : class
private delegate List<T> TDelegate();

_dctCahceActions = new Dictionary<string, TDelegate>();
 _dctCahceActions.Add("x", (() => { return Method1(); }));
_dctCahceActions.Add("y", (() => { return Method2(); }));
...

The problem is that Method1, Method2, and so on return a List of different types.
The main idea is to do something like
List<T> res = _dctCahceActions["x"].Invoke();
But the problem occurs at compile time because of the cast. How to solve this correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mletov, 2018-04-05
@mletov

Solved a problem
private delegate dynamic TDelegate();

D
Daniil Basmanov, 2018-04-05
@BasmanovDaniil

List implies that the type of the contents of the sheets is the same - type T, if objects from methods can be cast to it, then everything should be compiled.

using System;
using System.Collections.Generic;

public class MyClass<T> where T : class
{
    private Dictionary<string, Func<List<T>>> functions = new Dictionary<string, Func<List<T>>>();
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question