如何将方法返回类型设置为其当前所在类的相同类型

时间:2019-06-07 18:57:12

标签: c# class networking

此处是中级C#程序员。我正在编写一个网络包装程序,并希望每种类型的数据包都能够定义自己的“ OpenPacket”方法,该方法将采用与当前类相同类型的类的参数。我还想要另一个方法“ WriteToPacket”,该方法将返回与当前类相同类型的数据包。

例如。 MessagePacket类的WriteToPacket将返回MessagePacket。我将使用继承并仅返回Packet类型,但是每个数据包都有不同的变量。另外,我正在将其开发为一个库,因此我希望能够在dll之外定义新的数据包类型。

我有一个用于数据包类型的接口

public interface IPacket_Type<T> where T : class
{
    T OpenPacketFromMessage(NetIncomingMessage msg) ;
    NetOutgoingMessage PackPacketIntoMessage(NetOutgoingMessage msg, T packet);
}

我将其用作数据包的一部分

public class TestPacket : Packet, IPacket_Type<TestPacket> {
    public int testInt;

    public TestPacket(string packet_name) : base(packet_name){}

    public TestPacket OpenPacketFromMessage(NetIncomingMessage msg)
    {
        TestPacket packet = new TestPacket(packet_name);
        packet.testInt = msg.ReadInt32();

        return packet;
    }

    public NetOutgoingMessage PackPacketIntoMessage(NetOutgoingMessage msg, TestPacket packet)
    {
        msg.Write(packet_name);
        msg.Write(packet.testInt);
        return msg;
    }
}

在服务器端收到类名称后,我希望能够实例化此类。例如,创建一个TestPacket实例而不是一个包。我想到的一种方法是,使数据包类返回其当前类型,因此允许我将其用作基础,并始终返回该类的类型。

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:1)

在下面的代码中,我向您展示一些如何使用相同类的实例的示例:

public class Sample {
    // This method returns the same instance of the sample class
    public Sample ReturnSampleInstance() {
        return this;
    }

    // This method creates a completely new instance of the class with other data
    public Sample ReturnAnotherSampleInstance() {
        var sample = new Sample();
        // Perform some logic with the new sample instance or fill up some data
        return sample;
    }

    // This method receives an instance of the same class and returns it
    public Sample ReceivesSampleInstanceAndReturnIt(Sample sampleInstance) {
        return sampleInstance;
    }
}

如果您想使用一个接口,并且该接口的方法具有返回类型作为实现类,则可以按照以下步骤进行操作:

// Generic Interface 
public interface ISample<Timplementation> {
    Timplementation GetCurrentInstanceUsingAnInterface();
}

// Class that implements the interface and passes itself to the ISample interface as a generic parameter
public class Sample : ISample<Sample> {
    // This method returns the same instance of the sample class
    public Sample ReturnSampleInstance() {
        return this;
    }

    // This method creates a completely new instance of the class with other data
    public Sample ReturnAnotherSampleInstance() {
        var sample = new Sample();
        // Perform some logic with the new sample instance or fill up some data
        return sample;
    }

    // This method receives an instance of the same class and returns it
    public Sample ReceivesSampleInstanceAndReturnIt(Sample sampleInstance) {
        return sampleInstance;
    }

    // Get the current instance of the class through the method of the interface
    public Sample GetCurrentInstanceUsingAnInterface() {
        return this;
    }
}