The following code is a simplified version of what I have:
public interface IBase
{
Type Type { get; set; }
}
public class Derived<T> : IBase
{
public Derived(T val)
{
Value = val;
Type = typeof(Derived<T>);
Action = (val) => Console.WriteLine(val);
}
public T Value { get; set; }
public Type Type { get; set; }
public Action<T> Action { get; set; }
}
public class SomeClass
{
private List<IBase> _elements;
public SomeClass()
{
_elements = new()
{
new Derived<int>(15),
new Derived<string>("someString"),
new Derived<SomeEnum>(SomeEnum.SomeValue)
};
}
public void PrintValues()
{
foreach (var element in _elements)
{
// here I want to cast element to the type of Derived<T> and print its Value via Action delegate
var converted = // some logic for casting to type Derived<T>
converted.Action.Invoke(converted.Value);
}
}
}
I have SomeClass
which stores a collection of all Derived
instances that are typed as IBase
. The aim of this class is to invoke all the action delegates within the collection of Derived
instances. The problem is that SomeClass
does not know anything about the possible types for generic type of Derived
class.
I am struggling to implement conversion from IBase
interface to Derived<T>
in PrintValues
method to get access to its members.
Remark: making PrintValues
method of SomeClass
also generic will not help because SomeClass
is called by another class which also does not know anything about the possible types for generic type.
I guess this is a problem of bad code architecture but I cannot figure out how to resolve it.
Please let me know if I am not clear in my explanation of the problem.