Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hi All,

I will explain my scnerio. I have a static generic class like this.

C#
public static class Cls<T>


There is a generic function in this class like below.

C#
public static void Foo<K>()


The purpose of this function is to create a lambda expression of the type Action<T, K> and store it in a class member variable for use in other functions. My problem is that I cannot access the K type out of the function scope. So that I cannot create a Action<T, K> type class member variable. I cannot change the class signature like Cls<T,K> because different K should be processed against a single T type.

One solution I found that the Action<T, K> type function can be stored in a non generic Delegate variable and use the DynamicInvoke to execute the function. It will work but the execution time of DynamicInvoke is more than I expect. Is there any workaround for this? Any help you can give will be greatly appreciated.

Thanks,
Thomas
Posted

1 solution

Most likely, you are moving in wrong direction, but I cannot tell what to do for sure because you did not tell us the ultimate purpose of all this activity.

Instead, I'll try to explain you some concept of generics which you might miss.

You cannot get the actual type of T or K because they are not stored anywhere. It simply does not makes sense. Each time you use the generic type, for example, actually call its method, you instantiate it with some actual type which you substitute for T. In your case, the situation is more complex, because you store the static value. This static value is created each time you call the method Foo storing it. If you the result of this method (why, why you don't return it as a function result?) becomes unreachable, the situation is equivalent to the case when you never called the method. If you need more detail on it, you should better show the code using the stored static value calculated as a result of this call.

You could probably solve the problem by returning your lambda expression from this method; this way you can store it outside the instantiation of a generic class. However, the whole situation looks pathological to me. Chances are, you could come up with more reasonable design of your code. Again, I would probably advise something else if you could explain the ultimate purpose of all that.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900