Work with System.ComponentModel

I find it difficult to understand how the container / component model interacts with each other in C #. I get how a component contains a site object that contains information about the container and the component. But suppose I have 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 problems, it defines the Container (Entity) and the Component (Position), which is contained inside it.

However, if I call 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 rather cumbersome.

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

+6
source share
1 answer

You have not missed anything. There is no interface contract regarding which container may be inside. If you want to limit which components can be added to the container, you can overload the Add method and check the type of component to be 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); } } 
+2
source

All Articles