문제

I have multiple kinds of Action delegates. Take e.g.:

Action<float> floatAction;
Action<string> stringAction;

I want to store any one of them into one variable, and be able to invoke it later. Is that possible?

SomeSortOfType action = floatAction;
//or
SomeSortOfType action = stringAction;
SomeSortOfType.Invoke();

I could not find a basetype for the Action class, so I'm pretty clueless as to whether this is possible in a way.

Gr.Viller

도움이 되었습니까?

해결책

You can use Delegate class that is the base class for all delegate types.

For example:

Action<float> floatAction = (x) => Console.Write(x * 5);
Action<string> stringAction = Console.WriteLine;

Delegate d1 = floatAction;
d1.DynamicInvoke(4.3f);

d1 = stringAction;
d1.DynamicInvoke("Hello world");

다른 팁

You could use an Action<dynamic> (or Action<object> with casting) if you create new lambdas referencing your Action<>s:

Action<float> floatAction = x => Console.WriteLine(x*3);
Action<string> stringAction = Console.WriteLine;

Action<dynamic> dyn = o => floatAction(o);
dyn(1.5f);
dyn = o => stringAction(o);
dyn("Hello World!");

I'd say Selman22's solution is probably better, but I present this in case it's more useful to you.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top