Generic type with namespace restriction

Everyone knows

public class Test<T> where T : SomeBaseClass 

But is there a way to restrict T classes that exist in the namespace, for example

 public class Test<T> where T in SomeNamespace 

Best wishes

+6
source share
4 answers

Not. There is no way to limit the generic type to a namespace.

+12
source

Not. Constraints are a definition of behavior - whether it's just as a class, the implementation of a given interface, or something else. It's not about what namespace is defined in the class - it doesn't say anything about its behavior.

See Type Parameter Constraints for a summary of constraints.

+1
source

Namespace restrictions are not possible. In any case, this makes no sense, because anyone can create classes that are in the target namespace. Perhaps this will only affect the fact that you can limit it to a specific assembly.

It will be more if you can limit it to n types, such as the following lines (doesn't work):

 public T Create<T>() where T : { MyClass1, MyClass2 } 

See limitations

http://msdn.microsoft.com/en-us/library/d5x73970.aspx

+1
source

You could do this by creating an interface with an inner scope and using this in your generic expression, where is the sentence (the common class / method must be in the same assembly). Then you can use it only with classes in the same assembly that implement this interface.

If you needed to go through classes from another assembly, you could add the global :: InternalsVisibleToAttribute ("another assembly name") to the AssemblyInfo file.

All that has been said is still not like what one can try to achieve.

0
source

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


All Articles