简体   繁体   中英

Namespace constraint with generic class declaration

I would like to know if (and if so how) it is possible to define a namespace as a constraint parameter in a generic class declaration.

What I have is this:

namespace MyProject.Models.Entities <-- Contains my classes to be persisted in db

namespace MyProject.Tests.BaseTest <-- Obvious i think

Now the decleration of my 'BaseTest' class looks like so;

public class BaseTest<T>

This BaseTest does little more (at the time of writing) than remove all entities that were added to the database during testing. So typically I will have a test class declared as:

public class MyEntityRepositoryTest : BaseTest<MyEntity>

What i would LIKE to do is something similar to the following:

public class BaseTest<T> where T : <is of the MyProject.Models.Entities namespace>

Now i am aware that it would be entirely possible to simply declare a 'BaseEntity' class from which all entities created within the MyProject.Models.Entities namespace will inherit from;

public class BaseTest<T> where T : MyBaseEntity

but...I dont actually need to, or want to. Plus I am using an ORM and mapping entities with inheritance, although possible, adds a layer of complexity that is not required.

So, is it possible to constrain a generic class parameter to a namespace and not a specific type ?

It's not possible to create any such constraints to namespaces.

A more preferable workaround would be to make your generic class internal rather than public . This means that the class can only be directly instantiated and accessed by classes in the same assembly (unless you use the InternalsVisibleTo attribute). However, it can still be indirectly instantiated (ie as a protected/private member of a public class).

A namespace constraint would be of no value. Any third party could create a class and put that class into the same namespace.

The compiler won't perform this check for you. You could verify this constraint at runtime though, perhaps in a static constructor for your type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM