如何将对象绑定到列表?

时间:2014-11-13 02:31:43

标签: c# object generics reference bind

这不是一个Windows窗体应用程序,我不确定我是否使用了正确的术语。我试图将对象绑定到列表,因此当在列表之外修改对象时,这些更改将反映在列表中。我不完全确定如何开始,我的搜索只是不断回归" winform"数据源的答案,但这不是我想要的。以下是我到目前为止的情况:

如果您想测试它,可以将此代码复制到控制台应用程序中。注意循环遍历go.Getcomponents()的foreach不显示名称,因为我不认为当从列表中拉出时仍然引用被修改的对象。基本上我试图修改列表外的对象,但是当修改该对象时,列表中的对象也会被修改。

重要的是它可以被序列化,因为GameObject将通过网络传输,其中的数据将由服务器读取。

class Test
{
    public void TestStart()
    {
        GameObject go = new GameObject(); //create GameObject
        Dog dog = go.AddComponent<Dog>(); //Add a Dog component to the GameObject
        dog.name = "Fluffy";  //name the dog fluffy, this should be reflected in the GenericComponent list of GameObject
        Dog dog2 = go.AddComponent<Dog>();
        dog2.name = "Fuzzy";

        //loop through all dog components in GameObject go, doesn't print dog names :(
        foreach (Dog dg in go.GetComponents<Dog>())
        {
            Console.WriteLine(dg.name);
        }
        Console.ReadLine();
    }
}
[Serializable]
public class GameObject
{
    List<GenericComponent<Object>> componentList = new List<GenericComponent<Object>>();

    //returns first found in list.
    public T GetComponent<T>()
    {
        return (T)componentList.Find(c => c.component.GetType() == typeof(T)).component;
    }
    //add a component to component list.
    public T AddComponent<T>()
    {
        GenericComponent<Object> newComponent = new GenericComponent<Object>();//;(T)Activator.CreateInstance(typeof(T));
        newComponent.component = (T)Activator.CreateInstance(typeof(T));
        componentList.Add(newComponent);
        return (T)Activator.CreateInstance(typeof(T));
    }
    //returns all components of type T
    public List<T> GetComponents<T>()
    {
        List<T> r = new List<T>();
        for (int i = 0; i < componentList.Count; i++)
        {
            if (componentList[i].component.GetType() == typeof(T))
            {
                r.Add((T)componentList[i].component);
            }
        }
        return r;
    }
}
[Serializable]
public class GenericComponent<T> where T : new()
{
    public T component;
    public GenericComponent()
    {
        component = new T();
    }
}
[Serializable]
public class Dog
{
    public string name = "";
    public Dog() { }
    public Dog(string name)
    {
        this.name = name;
    }
}

1 个答案:

答案 0 :(得分:1)

在AddComponent方法中,您要添加一个组件,然后再返回另一个组件。相反,返回您添加的相同内容:

public T AddComponent<T>()
{
    GenericComponent<Object> newComponent = new GenericComponent<Object>();
    newComponent.component = (T)Activator.CreateInstance(typeof(T));
    componentList.Add(newComponent);
    return (T)newComponent.component;
}