Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with System.ComponentModel

I am having a bit of difficulty in understanding how the Container/Component model interacts with each other in C#. I get how the Component contains a Site object which has information about Container and Component. But, suppose I had the following code:

using System;
using System.ComponentModel;

public class Entity : Container {
    public string Foo = "Bar";
}

public class Position : Component {
    public int X, Y, Z;    
    public Position(int X, int Y, int Z){
        this.X = X;
        this.Y = Y;
        this.Z = Z;
    }
}

public class Program {

    public static void Main(string[] args) {

        Entity e = new Entity();
        Position p = new Position(10, 20, 30);

        e.Add(p, "Position");            

    }    

}

This works without issue, it defines a Container (Entity) and a Component (Position) that is contained inside it.

However, if I invoke p.Site.Container, it will return Entity, but as IContainer. That is, I would have to explicitly do something like (Console.WriteLine(p.Site.Container as Entity).Foo); if I wanted to access Foo. This seems quite cumbersome.

Am I missing something, or is there a better way to do what I want?

like image 716
Kyle Baran Avatar asked Dec 15 '12 16:12

Kyle Baran


People also ask

What is System ComponentModel?

The System. ComponentModel namespace provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components.

How do I add system ComponentModel composition?

all you have to do is go to project then add reference then find the system. componentmmodel. composition. Once you already added it.

What is .NET component model?

NET Component Model provides ability (through Site Services) to define separate Components , so they can communicate with each other in a loosely coupled way, and that each Component is easily replaceable.

What is the namespace for DataAnnotations in MVC?

ComponentModel. DataAnnotations Namespace. Provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls.


1 Answers

You're not missing anything. There is no interface contract regarding what container a component can be inside. If you want to restrict what kind of components can be added to the container you can overload the Add method and do a check of the type of component being added:

public class Entity : Container {
    public string Foo = "Bar";

    public virtual void Add(IComponent component) {
        if (!typeof(Position).IsAssignableFrom(component.GetType())) {
            throw new ArgumentException(...);
        }
        base.Add(component);
    }
}
like image 95
Eilon Avatar answered Oct 27 '22 01:10

Eilon