Using a generic type from another generic parameter

I have a question about .net generics. Consider the following code:

public abstract class Test<TKey> { TKey Key { get; set; } } public class Wrapper<TValue, TKey> where TValue : Test<TKey> { public TValue Value { get; set; } } 

Now, using this code, I could do something like this:

 Wrapper<Test<int>, int> wrapper = new Wrapper<Test<int>, int>(); 

An int parameter must be specified twice. Is it possible to modify the definition of Wrapper to require TValue to be a generic type and use this "nested" type of the typical type set to the type parameter of TKey?

+4
source share
1 answer

I would say that it depends on whether you really need to provide your Value property as a specific TValue , where the TValue comes from Test<T> . In other words, do you need to expose the functionality available only for derived classes, or can you just expose Test<T> with all the functionality of the base class?

In the latter case, you can simplify the definition of your class:

 public class Wrapper<TKey> { public Test<TKey> Value { get; set; } } 

As for the exact functionality you are looking for: I do not believe that in the current version of C # something completely similar is available.

However, another option in your case might be to actually use your Wrapper class as the base class:

 public abstract class Test<TKey> { TKey Key { get; set; } } public abstract class Wrapper<TValue, TKey> where TValue : Test<TKey> { public TValue Value { get; set; } } public class TestWrapper<TKey> : Wrapper<Test<TKey>, TKey> { } // ... some code somewhere var tw = new TestWrapper<int>(); Test<int> value = tw.Value; 
+1
source

Source: https://habr.com/ru/post/1311972/


All Articles