首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用System.ComponentModel

使用System.ComponentModel
EN

Stack Overflow用户
提问于 2012-12-16 00:40:17
回答 1查看 6.3K关注 0票数 6

在理解容器/组件模型如何在C#中彼此交互时,我遇到了一些困难。我知道组件如何包含一个Site对象,该对象包含关于Container和Component的信息。但是,假设我有以下代码:

代码语言:javascript
复制
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");            

    }    

}

这是没有问题的,它定义了一个容器(实体)和一个包含在其中的组件(位置)。

但是,如果我调用p.Site.Container,它将返回Entity,但作为IContainer返回。也就是说,如果我想访问Foo,我必须显式地执行类似于(Console.WriteLine(p.Site.Container as Entity).Foo);的操作。这看起来相当麻烦。

我是否遗漏了什么,或者有没有更好的方法来做我想做的事情?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-12-16 00:53:08

你不会错过任何东西的。没有关于组件可以包含在哪个容器中的接口约定。如果想要限制可以添加到容器中的组件类型,可以重载Add方法并检查所添加的组件的类型:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13894088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档