开发者

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 BaseTe开发者_运维百科st<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 (i.e. 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 best approach is to create an interface and use this Interface in your classes, then add this interface to your constraints

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜