如何将类类型发送到另一个类并创建此类的实例?

时间:2018-05-16 11:54:53

标签: c# .net class generics networking

我在图书馆工作,这将有助于为各种应用程序实现专用服务器(主要是我的目标是游戏)。我正在使用套接字,我想实现某种命令系统,用户可以在服务器上调用函数。 我有一个问题,因为我想让一个用户在他创建的类中实现可交互的命令环境,我的库需要知道。 我创建了这个模板示例,说明它是如何构建的:

由我实现,是图书馆的一部分(非常简化):

public class UserInfo //class containing info about user
{
    public int id;

    public UserInfo(int _id)
    {
        id = _id;
    }
}

public class UserManager
{
    List<UserInfo> userInfos;

    public UserManager(List<UserInfo> _userInfos) //We get out infos from somewhere...
    {
        userInfos = _userInfos; //...and keep reference to them

        //SetupChildClassAndInfos();
    }

    //I'd like to have something like that BUT I don't know 
    //how ChildClass is called so I can't just type it like here

    /*
    List<ChildClass> childs = new List<ChildClass>();

    void SetupChildClassAndInfos()
    {
        foreach (var userInfo in userInfos)
        {
            ChildClass child = new ChildClass();
            child.someInfo = userInfo;
            childs.Add(child);
        }
    }
    */


    //I tried working with generics but failed miserably xd
    List<T> childs = new List<T>();
    public void GetChildClass<T>()
    {
        foreach (var userInfo in userInfos)
        {
            T child = new T();
            child.userInfo = userInfo;
            childs.Add(child);
        }
    }
    //of course it doesn't work and makes no sense xD but I hope you kinda g
    //get what I'm trying to accomplish
}

public class UserClass //Base class for further implementation containing 
                       //userInfo that user needs to know about
{
    public UserInfo userInfo;
}

其他人的示例实现,我不知道如何调用ChildClass:

public class ChildClass : UserClass //there needs to be access to UserClass informations
{
    CustomManager customManager;

    [Command] //attribute making method be called automaticly when is the right time
    public void Message(string _message) //A method made by a user BUT(!) he will never use it directly
    {
        customManager.ReceiveMessage(userInfo.id, _message);
    }
}
public class CustomManager
{
    UserManager userManager; //assume we somehow have reference

    public CustomManager()
    {
        userManager.GetChildClass<ChildClass>(); //sending information in beginning to infoManager how I implemented my ChildClass (doesn't work)
    }


    public void ReceiveMessage(int _id, string _message)
    {
        Debug.Log("We got message: " + _message + " from user with id: " + _id);
    }
}

所以我的问题是如何将自定义类发送到UserManager并创建此类的实例? 也许我写的东西没有任何意义,我的方法很愚蠢,随意批评。

2 个答案:

答案 0 :(得分:0)

使CustomManager成为通用类

Generic Property in C#

OR

通过使用spring.net或Unity框架实现依赖性反转主体来使用依赖注入。

答案 1 :(得分:0)

只有字典IReadOnlyDictionary<string, object>有什么问题?你关注价值类型的拳击吗?对代码的一瞥让我相信,继续使用更复杂的解决方案还为时尚早。因此,将这个部分抽象为一个接口并以最简单的方式实现该部分是有意义的:借助于字典(a-ka JavaScript方式)。