对象类型与继承类中的类型相同

时间:2018-02-15 00:03:04

标签: c# inheritance

我想从我的Connection类仅返回Account对象,并且效果很好。

public class Connection : Account
{
    public Account GetAccountData ()
    {
        Account acc = (Account) MemberwiseClone(); 
        return acc;
    }
}

但acc.GetType()返回" Connection"。 我究竟做错了什么?我需要让acc.GetType()等于" Account"。 #EDITED#好的,这是一段需要从Connection获取Account对象的代码。

Connection ClientConnection = 
FindConnectionViaIdentifier(connection.RemoteUniqueIdentifier);
if (ClientConnection != null)
{
Account account = ClientConnection.GetAccountData();
Debug.Log(account.GetType().ToString());
// Serializing
 om.Write(PacketSerialization.SerializeToByteArray<Account>(account));
}`

所以我试图序列化我从Connection类获得的Account对象,但是我不能序列化它,因为它的类型不是Account而是Connection。这是序列号:

static class PacketSerialization
{
    public static byte[] SerializeToByteArray<T>(this T obj) where T : class
    {
        if (obj == null)
        {
            return null;
        }
        using (var ms = new MemoryStream())
        {
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(ms, obj);
            return ms.ToArray();
        }
    }

    public static T Deserialize<T>(this byte[] byteArray) where T : class
    {
        if (byteArray == null)
        {
            return null;
        }
        using (var memStream = new MemoryStream(byteArray))
        {
            var serializer = new DataContractSerializer(typeof(T));
            var obj = (T)serializer.ReadObject(memStream);
            return obj;
        }
    }
}

编辑这是帐户类的外观

[Serializable, DataContract(Namespace = "Alveria Data")]
public class Account
{
    [DataMember] public string AccountName { get; set; }
    [DataMember] public string Token { get; set; }
    [DataMember] public List<Character> CharacterList { get; set; }

    public Account(string accountName, string token, List<Character> characterList)
    {
        this.AccountName = accountName;
        this.Token = token;
        this.CharacterList = characterList;
    }
}

0 个答案:

没有答案