简体   繁体   English

C#返回抽象类中的派生类

[英]C# return derived class in abstract class

I would like to create a NMEA message parser for GPGGA, GPGSV, and etc. Each of the message is derived from the abstract class NMEAMsg. 我想为GPGGA,PGPSV等创建NMEA消息解析器。每个消息都派生自抽象类NMEAMsg。

So I would need to overwrite the parseToken for each of the message type: 因此,我需要为每种消息类型覆盖parseToken

But, I do not know how to return the derived class in the abstract class? 但是,我不知道如何在抽象类中返回派生类?

I am getting Invalid CastException unhandled by user when run this code 运行此代码时,我收到Invalid CastException unhandled by user

I need the public static NMEAMsg parse(string src) method to return the derived class like GGA or GSA 我需要public static NMEAMsg parse(string src)方法来返回派生类,例如GGAGSA

//NMEAMsg.cs
public abstract class NMEAMsg
{
    public static NMEAMsg parse(string src)
    {
        NMEAMsg nmeaMsg = (NMEAMsg)new object();

        var tokens = src.Split(',');
        tokens[tokens.Length - 1] = tokens[tokens.Length - 1].Split('*')[0];

        nmeaMsg.parseTokens(tokens);

        return nmeaMsg;
    }

    public abstract void parseTokens(string[] tokens);
}


//GGA.cs
public class GGA : NMEAMsg
{
    public double latitude;
    public double longitude;

    public override void parseTokens(string[] tokens)
    {
        Double.TryParse(tokens[1], out this.latitude);
        Double.TryParse(tokens[2], out this.longitude);
    }
}

//GSA.cs
public class GSA : NMEAMsg
{
    public double hdop;

    public override void parseTokens(string[] tokens)
    {
        Double.TryParse(tokens[1], out this.hdop);
    }
}

//main.cs
string src = "$GPGGA,123,323*23";

var data = NMEAMsg.parse(src);

if (data is GGA) {
   //Do stuff here  
} else if (data is GSA) {
   //Do stuff here
}

You'll probably need something like this: 您可能需要这样的东西:

public static NMEAMsg parse(string src)
{
    var tokens = src.Split(',');
    tokens[tokens.Length - 1] = tokens[tokens.Length - 1].Split('*')[0];

    NMEAMsg nmeaMsg = null;
    if (tokens[0] == "$GPGGA")
    {
        nmeaMsg = new GGA();
    }
    else if (tokens[0] == "$GPGSA")
    {
        nmeaMsg = new GSA();
    }
    else
    {
        throw new Exception("Unrecognized type: " + tokens[0]);
    }

    nmeaMsg.parseTokens(tokens);

    return nmeaMsg;
}

Where you instantiate the correct class based on the beginning of the parsed string, and then call the specific class' parseTokens() method implementation to complete the parsing. 在此,您将基于已解析的字符串的开头实例化正确的类,然后调用特定类的parseTokens()方法实现来完成解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM