名称空间约束与泛型类声明

编程入门 行业动态 更新时间:2024-10-26 06:33:11
本文介绍了名称空间约束与泛型类声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

我的是这样的:

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).

更多推荐

名称空间约束与泛型类声明

本文发布于:2023-11-09 10:30:53,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:声明   名称   空间   泛型类

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!