简体   繁体   中英

Find TypeOf Child class when casted as Parent

I have a Partial View that I want be able to use with several different models. Is there any way to find out what the Child class of an object is when it is being passed in as its parent?

For example:

Model:

public class Animal { }
public class Dog : Animal { }
public class Cat : Animal { }

Controller:

public class AnimalActionController : Controller
{
    public ActionResult MakeAnimalSound(Animal animal)
    {
       if (animal is Dog)
       {
         return PartialView("~/Views/_AnimalActionView.cshtml", new{sound="Woof"});
       }
       if (animal is Cat)
       {
         return PartialView("~/Views/_AnimalActionView.cshtml", new{sound="Meow"});
       }
    }
}

Parent View of Dog page:

@model Test.Models.Dog
@Html.Action("MakeAnimalSound", "AnimalAction", new { Model })

Right now if I were to do something like this example the if statements in the Controller only see animal as Animal and not as Dog or Cat which it originally was.

Anyone know how to do this? I feel like it should be simple.

A better choice for this would be to do something like this. Testing class types is a poor design and considered a code smell in most cases (sometimes it's necessary, but there's usually other ways to accomplish what you want without it):

public class Animal
{
     public virtual Sound {get;}
}
public class Dog : Animal
{
     public override Sound {get {return "Woof";}}
}
public class Cat : Animal
{
     public override Sound {get {return "Meow";}}
}

public ActionResult MakeAnimalSound(Animal animal)
{
   return PartialView("~/Views/_AnimalActionView.cshtml", new{sound=animal.Sound});
}

If you call the object's GetType() method, you will get an object that will tell you everything you need to know. See the MSDN page on System.Type .

The following program outputs Child .

internal class Parent {
    private string Something { get; set; }
}

internal class Child : Parent {
    private int SomethingElse { get; set; }
}

internal class Program {

    private static void Main(string[] args) {
        Parent reallyChild = new Child();
        Console.WriteLine(reallyChild.GetType().Name);
        Console.ReadLine();
    }
}

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