gpt4 book ai didi

c# - 使用 System.ComponentModel

转载 作者:太空狗 更新时间:2023-10-29 21:54:46 27 4
gpt4 key购买 nike

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

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,它将返回实体,但作为 IContainer。也就是说,如果我想访问 Foo,我将不得不显式地执行 (Console.WriteLine(p.Site.Container as Entity).Foo); 之类的操作。这看起来很麻烦。

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

最佳答案

您没有遗漏任何东西。没有关于组件可以在哪个容器中的接口(interface)契约。如果您想限制可以添加到容器中的组件类型,您可以重载 Add 方法并检查要添加的组件类型:

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);
}
}

关于c# - 使用 System.ComponentModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13894088/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com