Практическое руководство. Переход по отношениям с помощью UML API

В Visual Studio Ultimate модель состоит из элементов, связанных разными видами отношений.В этом разделе описывается переход по модели в программном коде.

Перемещение отношений

Ee330927.collapse_all(ru-ru,VS.110).gifЛюбое отношение

Используйте GetRelatedElements<T>(), чтобы найти все элементы, соединенные с заданным элементом.Чтобы переместить связи любых видов, задайте T значение IRelationship, либо используйте более конкретный тип, такой как IAssociation, чтобы переместить только этот тип.

IElement anElement;
// Select all elements related to anElement.
Context.CurrentDiagram.SelectShapes (
   anElement.GetRelatedElements<IRelationship>()
    .SelectMany(e=>e.Shapes()).ToArray());

Используйте GetRelatedLinks<T>(), чтобы найти все отношения, соединенные с элементом.

// Process all relationships connected to an element.
foreach (IRelationship relationship in 
   anElement.GetRelatedLinks<IRelationship>())
{
  Debug.Assert(relationship.SourceElement == anElement
      || relationship.TargetElement == anElement);
}

Ee330927.collapse_all(ru-ru,VS.110).gifАссоциация

Ассоциация — это отношение между двумя свойствами, каждое из которых принадлежит к классификатору.

IClassifier classifier; // class, interface, component, actor, ...
// Get all the associations sourced from this classifier
foreach (IProperty p in classifier.GetOutgoingAssociationEnds())
{
  // p represents the end further end of an association.
  IType oppositeElement = p.Type; 
    // The type to which this association connects classifier
  
  IProperty oppositeProperty = p.Opposite;
    // The nearer end of the association.
  Debug.Assert(oppositeProperty.Type == classifier);
  IAssociation association = p.Association;
  Debug.Assert(association.MemberEnds.Contains(p)
     && association.MemberEnds.Contains(oppositeProperty));
}

Ee330927.collapse_all(ru-ru,VS.110).gif Обобщение и реализация

Получение доступа к противоположным окончаниям обобщения.

foreach (IClassifier supertype in classifier.Generals) {…}
foreach (IClassifier subtype in classifier.GetSpecifics()) {…}
Access the relationship itself:
foreach (IGeneralization gen in classifier.Generalizations) 
{ Debug.Assert(classifier == gen.Specific); }

/// InterfaceRealization:
IEnumerable<IInterface> GetRealizedInterfaces
    (this IBehavioredClassifier classifier);
IEnumerable<IBehavioredClassifier> GetRealizingClassifiers
    (this IInterface interface);
 

Ee330927.collapse_all(ru-ru,VS.110).gifЗависимость

/// Returns the elements depending on this element
IEnumerable<INamedElement> GetDependencyClients(this INamedElement element); 
/// Returns the elements this element depends on
IEnumerable<INamedElement> INamedElement GetDependencySuppliers(this INamedElement element);
 

Ee330927.collapse_all(ru-ru,VS.110).gifГраница действия

/// Returns the nodes targeted by edges outgoing from this one
IEnumerable<IActivityNode> GetActivityEdgeTargets(this IActivityNode node);
/// Returns the nodes sourcing edges incoming to this one
IEnumerable<IActivityNode> GetActivityEdgeSources(this IActivityNode node);
 

Ee330927.collapse_all(ru-ru,VS.110).gifСоединитель (сборка и делегирование)

/// Returns the elements connected via assembly 
/// or delegation to this one
IEnumerable<IConnectableElement> GetConnectedElements(this IConnectableElement element);
 

Ee330927.collapse_all(ru-ru,VS.110).gifСообщения и линии жизни

IEnumerable<IMessage> GetAllOutgoingMessages(this ILifeline  lifeline); 
// both from lifeline and execution occurrences
IEnumerable<IMessage> GetAllIncomingMessages(this ILifeline  lifeline);
ILifeline GetSourceLifeline(this IMessage message); 
    // may return null for found messages
ILifeline GetTargetLifeline(this IMessage message);  
    // may return null for lost messages
 

Ee330927.collapse_all(ru-ru,VS.110).gifИмпорт пакета

IEnumerable<IPackage>GetImportedPackages(this INamespace namespace);
IEnumerable<INamespace> GetImportingNamespaces(this IPackage package);
 

Ee330927.collapse_all(ru-ru,VS.110).gifРасширение и включение варианта использования

IEnumerable<IUseCase>GetExtendedCases(this IUseCase usecase);
IEnumerable<IUseCase>GetExtendingCases(this IUseCase usecase);
IEnumerable<IUseCase>GetIncludedCases(this IUseCase usecase);
IEnumerable<IUseCase>GetIncludingCases(this IUseCase usecase);

 Перечисление отношений

Все свойства UML-модели, возвращающие несколько значений, соответствуют интерфейсу IEnumerable<>.Значит, можно использовать Linq Query Expressions и методы расширения в пространстве имен System.Linq.

Примеры.

from shape in     Context.CurrentDiagram.GetSelectedShapes<IClassifier>()
where shape.Color == System.Drawing.Color.Red
select shape.Element

См. также

Основные понятия

Расширение моделей и схем UML

Практическое руководство. Навигация по UML-модели