名称空间约束与泛型类声明 [英] Namespace constraint with generic class declaration

查看:153
本文介绍了名称空间约束与泛型类声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在泛型类声明中将名称空间定义为约束参数。



我的是这样的:

namespace MyProject.Models.Entities< - 包含我的类将被保存在数据库中



命名空间 MyProject.Tests。 BaseTest< - 显而易见,我认为



现在,我的'BaseTest'类的删减看起来像这样;

  public class BaseTest< T> 

这个 BaseTest 写入时间)而不是删除在测试期间添加到数据库的所有实体。因此,通常我会将测试类声明为:

  public class MyEntityRepositoryTest:BaseTest< MyEntity> 

我想要做的是类似于以下的内容:

  public class BaseTest< T>其中T:<是MyProject.Models.Entities命名空间> 

现在我意识到完全可以简单地声明一个'BaseEntity'类在 MyProject.Models.Entities 命名空间内创建的实体将继承自;

  public class BaseTest< T>其中T:MyBaseEntity 

但是...我实际上不需要,或者想要。另外,我使用了一个ORM,并且使用继承映射实体,虽然可能,但增加了一层不需要的复杂性。

那么,是否有可能约束泛型类参数传递给命名空间而不是特定类型?

解决方案

不可能为命名空间创建任何这样的约束。



更好的解决方法是使您的泛型类内部而不是 public 。这意味着该类只能直接 实例化并可以被同一程序集中的类访问(除非使用 InternalsVisibleTo 属性)。然而,它仍然可以被间接实例化(即作为public类的protected / private成员)。

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 (i.e. as a protected/private member of a public class).

这篇关于名称空间约束与泛型类声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆