从强制班获得原始班

时间:2019-04-23 04:13:32

标签: c#

例如,我有三个类:public class LoadApplications extends AsyncTask<Void, Void, List<ActivityManager.RunningServiceInfo>> { @Override protected List<ActivityManager.RunningServiceInfo> doInBackground(Void... arg0) { return runningServices(); } @Override protected void onPostExecute(List<ActivityManager.RunningServiceInfo> applist) { // call super listadapter = new AppAdapter(Taskmanager.this, R.layout.list_item, applist); listView.setAdapter(listadapter); progressDialog.dismiss(); //other works } } var smooth:int=1; private var targetPosition:Vector3; function Update () { if(Input.GetKeyDown(KeyCode.Mouse0)) { var playerPlane = new Plane(Vector3.up, transform.position); var ray = Camera.main.ScreenPointToRay (Input.mousePosition); var hitdist = 1.0; if (playerPlane.Raycast (ray, hitdist)) { var targetPoint = ray.GetPoint(hitdist); targetPosition = ray.GetPoint(hitdist); var targetRotation = Quaternion.LookRotation(targetPoint - transform.position); } } transform.position = Vector3.Lerp (transform.position, targetPosition, Time.deltaTime * smooth); } Animal;其中Dog是抽象类,并将其属性继承到CatAnimal。说我的程序,我有一个用户可以输入的任意列表(我正在C#Form上执行此操作)。因此,我将所有输入(无论它们属于Dog还是Cat类别)存储到我的Cat中。

现在,我想从Dog检索所述实例化的类并检索其原始类,无论是List<Animal>还是List<Animal>。有办法吗?

3 个答案:

答案 0 :(得分:5)

在最新的C#中,您可以执行以下操作:

Animal animal;
if (animal is Cat cat)
{
   cat.Meow();
}

答案 1 :(得分:3)

using System.Collections.Generic;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Animal> animals = new List<Animal> { new Cat(), new Cat(), new Dog(), new Cat(), new Dog() };

            var dogs = animals.OfType<Dog>().ToList();
            dogs.ForEach(dog => dog.Bark());

            var cats = animals.OfType<Cat>().ToList();
            cats.ForEach(cat => cat.Meow());

            var actualTypes = animals.Select(animal => animal.GetType()).ToList();
        }

        abstract class Animal { }

        class Dog : Animal { public void Bark() { } }

        class Cat : Animal { public void Meow() { } }
    }
}

答案 2 :(得分:1)

您可以使用GetType来获取类的类型。

List<Animal> lstA = new List<Animal>();
        lstA.Add(new Cat());
        lstA.Add(new Dog());
        foreach(Animal a in lstA)
        {
            Console.WriteLine("Type of {0}", a.GetType());
        }

abstract class Animal
{}
class Cat : Animal
{}
class Dog : Animal
{}