我有一个通用的 C# 类,它看起来像这样:
public class Database<T>
where T : class, IModel, new()
{
//Some code ...
}
T 应该实现接口(interface) IModel 并且 T 必须是一个具有空构造函数的类。
问题是,这在 UML 类图中看起来如何。
谢谢你。
最佳答案
简而言之:
UML 为此目的使用类模板:
为此,您必须在某处(在 C# 配置文件中?)定义 NewConstraint
是一个特殊的接口(interface),它要求实现类有一个无参数的构造函数。或者,您可以跳过 NewConstraint
并添加一个简单的 UML 约束(例如,带有明文约束的注释 { T shall have a parameterless constructor }
)
关于模板参数的更多解释
有关 UML 分类器模板语法的更多信息,请参见 UML 规范(第 103 页):
A ClassifierTemplateParameter extends the notation for a TemplateParameter to include an optional type constraint:
<classifier-template-parameter> ::=
<parameter-name> [ ‘:‘ <parameter-kind> ] [‘>’ <constraint>]
[‘=’ <default>]
<constraint> ::= [‘{contract }’] <classifier-name>*
The parameter-kind indicates the metaclass of the parameteredElement. It may be suppressed if it is ‘Class.’
The classifier-name of constraint designates a
constrainingClassifier
, of which there may be zero or more, with the meaning specified in the semantics above. The ‘contract’ option indicates that allowSubstitutable is true.
由于我误解了
{contract}
我自己,首先将它与普通约束混淆,让我们澄清这个重要提示:{contract} xxx
表示该参数允许使用与 xxx
具有相同合约的分类器替换该参数.当参数是受特定接口(interface)约束的类时,这是必需的。 xxx
(不带 {contract}
)表示参数必须是 xxx
或者它的专业。因此,这不能用于必须实现接口(interface)的类,因为该类是接口(interface)的实现而不是特化。 在您的情况下,参数将是:
T : class > {contract} IModel NewConstraint
但由于默认情况下 class 是参数类型,因此可以简化为:T > {contract} IModel NewConstraint
关于c# - UML 中的通用类型约束(where 子句),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44244891/