简体   繁体   中英

Upcasting and Downcasting in c#

I have a setup like this:

public class PseudoContext : DbContext
{
    public DbSet<Account> Accounts {get; set;}

    public PseudoContext()
    {
        Accounts = new PseudoDbSet<Account>();
    }
}

public class PseudoDbSet<T> : DbSet<T> {}

So at runtime, Accounts should be of type PseudoDbSet<Account> ?

When I try to access Accounts via DbSet<Account> accountsSet = context.Accounts; , I cannot downcast it to via var tempSet = (PseudoDbSet<Account>)accountsSet , I get the following runtime exception:

Test method RoleManagerTest.PseudoContextTest.Add_ValidAccount_AccountAdded threw exception: System.InvalidCastException: Unable to cast object of type 'System.Data.Entity.DbSet 1[RoleManager.Models.Account]' to type 'RoleManager.Models.PseudoDbSet 1[RoleManager.Models.Account]

Why is that?

Edited to include some more information.

Look at this example code:

using System;

namespace Demo
{

    public class DbSet<T> { }

    public class Account { }

    public class PseudoContext
    {
        public DbSet<Account> Accounts {get; set;}

        public PseudoContext()
        {
            Accounts = new PseudoDbSet<Account>();
        }
    }

    public class PseudoDbSet<T> : DbSet<T> {}

    class Program
    {

        static void Main(string[] args)
        {

            PseudoContext ct = new PseudoContext();
            PseudoDbSet<Account> db = (PseudoDbSet<Account>)ct.Accounts;

            Console.WriteLine(typeof(PseudoDbSet<Account>).FullName);
            Console.WriteLine(ct.Accounts.GetType().FullName);

            Console.ReadLine();

        }
    }
}

It works fine, because all classes are correctly inherited.

In your code, something is wrong with the DbSet class from which PseudoDbSet inherits. Try to pull out FullName from the two types and compare them with full name of the DbSet type at the place where the downcast fails. In my example, these two types are the same and everything goes fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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