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?
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.
all you have to do is go to project then add reference then find the system. componentmmodel. composition. Once you already added it.
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.
ComponentModel. DataAnnotations Namespace. Provides attribute classes that are used to define metadata for ASP.NET MVC and ASP.NET data controls.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With