【发布时间】:2015-10-25 01:52:07
【问题描述】:
我正在使用 ECS 架构,其中 abstractcomponent 类的组件仅使用值类型,从不引用类型。我希望基础 abstractcomponent 类包含 1 和 1 浅拷贝方法,而不必为每个单独的具体类重新实现。
有什么想法吗? C#?
/// <summary>
/// Only an empty classification/tag class. (Every last component is POD -- no exceptions!)
/// </summary>
public abstract class AbstractComponent
{
public T CreateShallowClone(AbstractComponent c) where T : AbstractComponent
{
return (T)c.MemberwiseClone();
}
}
[Serializable]
public sealed class Entity : Identifiable
{
public Entity() : base()
{
}
public bool IsEnabled { get; set; } = false;
private Dictionary<Type, AbstractComponent> Components { get; set; } = new Dictionary<Type, AbstractComponent>();
public void AddComponent(AbstractComponent c)
{
Components.Add(c.GetType(), c);
}
public void RemoveComponent<T>() where T : AbstractComponent<T>
{
if (!Components.Remove(typeof(T))) {
throw new KeyNotFoundException();
}
}
public bool HasComponent<T>() where T : AbstractComponent<T>
{
if (Components.ContainsKey(typeof(T)))
{
return true;
}
else
{
return false;
}
}
public T GetComponent<T>() where T : AbstractComponent<T>
{
AbstractComponent<T> c;
if (!Components.TryGetValue(typeof(T), out c))
{
throw new KeyNotFoundException();
}
return c as T;
}
public void Destroy()
{
Components = null;
}
}
【问题讨论】:
-
你能举一个你想做的代码的例子,即使它是错的?
-
public T CreateShallowClone(AbstractComponent c) where T : AbstractComponent { return (T)c.MemberwiseClone(); } } }
-
请编辑您的帖子并将代码放在那里,它在评论中完全不可读。