简体   繁体   English

具有泛型类声明的命名空间约束

[英]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.Models.Entities < - 包含要在db中保留的类

namespace MyProject.Tests.BaseTest <-- Obvious i think namespace MyProject.Tests.BaseTest < - 我觉得很明显

Now the decleration of my 'BaseTest' class looks like so; 现在我的'BaseTest'类的变化看起来像这样;

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. BaseTest (在编写本文时)执行的操作比删除测试期间添加到数据库的所有实体要多得多。 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; 现在我知道完全可以简单地声明一个'BaseEntity'类, MyProject.Models.Entities命名空间中创建的所有实体都将从该类继承;

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. 另外,我使用ORM和带有继承的映射实体,虽然可能,但增加了一层不需要的复杂性。

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 . 更优选的解决方法是使您的泛型类internal而不是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). 这意味着该类只能由同一程序集中的类直接实例化和访问(除非您使用InternalsVisibleTo属性)。 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. 您可以在运行时验证此约束,可能在您的类型的静态构造函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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