Action construct is generic but can that support generic type inside it?
The code snippet shown below is what I'm trying to achieve.
I'm aware of that there are other ways to do it but I am curious whether it can be achieved within an Action construct.
void SomeMethod()
{
Action<int> Initialize = //<T> and where T is all that stuff
(index) =>
{
T obj = new T();
obj.Initialize(index);
obj.DoWork();
};
Initialize<TypeA>(1);
Initialize<TypeB>(2);
}
No, basically - or at least, not within a single instance of an Action
- a single instance is inherently closed in terms of generics. Obviously you could use a regular generic method Initialize<T>
. If you need a single Action
, then it might need to take the type as a parameter:
Action<Type, int> init = (type, index) => {
ISomeInterface obj = (ISomeInterface)Activator.CreateInstance(type);
obj.Initialize();
obj.DoWork();
};
init(typeof(TypeA), 1);
init(typeof(TypeB), 2);
Otherwise:
void Initialize<T>(int index) where T : new(), ISomeInterface {
T obj = new T();
obj.Initialize();
obj.DoWork();
}
void SomeMethod() {
Initialize<TypeA>(1);
Initialize<TypeB>(2);
}
You can create Action<int>
delegates to represent separately Initialize<TypeA>(int)
and Initialize<TypeB>(int)
, but not both at the same time, and not the open Initialize<T>(int)
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments