Как я могу установить метод, возвращающий тип, такой же, как класс, в котором он сейчас находится - PullRequest
0 голосов
/ 07 июня 2019

Средний C # программист здесь. Я пишу сетевую оболочку и хочу, чтобы каждый тип пакета мог определять свой собственный метод OpenPacket, который будет принимать параметр класса того же типа, что и текущий класс. Я также хочу другой метод 'WriteToPacket', который будет возвращать пакет того же типа, что и его текущий класс.

Например. WriteToPacket класса MessagePacket вернет MessagePacket. Я бы использовал наследование и просто возвращал тип пакета, но каждый пакет имеет разные переменные. Кроме того, я разрабатываю его как библиотеку, поэтому я хотел бы, чтобы новые типы пакетов могли быть определены за пределами 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 Ответ

1 голос
/ 07 июня 2019

В следующем коде я покажу вам несколько примеров работы с экземплярами одного и того же класса:

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;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...