簡體   English   中英

轉換為父類時查找TypeOf Child類

[英]Find TypeOf Child class when casted as Parent

我有一個局部視圖,希望可以與幾種不同的模型一起使用。 當以對象的父類形式傳遞對象時,有什么方法可以找出它的子類?

例如:

模型:

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

控制器:

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"});
       }
    }
}

狗頁面的父視圖:

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

現在,如果我要執行類似此示例的操作,那么Controller中的if語句只會將動物視為動物,而不是原來的動物是狗或貓。

有人知道怎么做嗎? 我覺得這應該很簡單。

一個更好的選擇是做這樣的事情。 測試類類型是一個糟糕的設計,並且在大多數情況下被認為是代碼的味道(有時是必須的,但是通常有其他方法可以在沒有它的情況下完成您想要的工作):

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});
}

如果調用對象的GetType()方法,則會得到一個對象,該對象將告訴您所有您需要了解的內容。 請參閱System.Type上的MSDN頁面

以下程序輸出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();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM