T
T
TheTalion2016-10-31 00:08:50
C++ / C#
TheTalion, 2016-10-31 00:08:50

Search in the sheet of the base class of the object of the class of the heir, how to implement?

I can't figure out how to search not by the base class, but by the descendant class.
Example:

public class GameObject //базовый класс
  {
    public int m_perem;
    public GameObject(int _perem)
    {_perem= m_perem;}

public class Mouse : GameObject // класс наследник
  {
    public int m_conId;
    
    public Mouse( int _perem, int _conId): base (_perem)
    {m_conId = _conId;} }

Now the body with the leaf:
public class Main
  {
    public static void Main()
    {
var m_gameObjectList = new List<GameObject>(); //создаю типизированный лист с объектами базового класса
m_gameobjlist.Add(new Mouse(_perem, m_conId));//добавляю новый объект-наследник
m_gameobjlist.Find((GameObject x) => x._perem.Equals(что-то тут) );// так - поиск работает
m_gameobjlist.Find((Mouse x) => x._perem.Equals(что-то тут) );// а вот так уже ошибка 
//невозможно преобразовать лямбда выражение в тип делегата "Predicate<GameObject>", так как типы параметров не совпадают с типами параметров делегата 
}
}

How can I make the program understand that I need to look for an object of the Mouse class and compare the GameObject predicator with Mouse?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vyacheslav Zolotov, 2016-10-31
@SZolotov

Something like this. BUT! If your logic is based on the definition of types - something is wrong in the architecture.

class A
    {
        public virtual int AProp { get; } = 1;
    }

    class B : A
    {
        public override int AProp { get; } = 2;
    }
    class C : A
    {
        public override int AProp { get; } = 3;
    }
    class Program
    {
        static void Main(string[] args)
        {
            var aList = new List<A>(Enumerable.Repeat(new C(), 10));
            aList.AddRange(Enumerable.Repeat(new B(), 10));
            var a = aList.FirstOrDefault(x => x is B);
            var b = (B) a;
        }
    }
}

M
MonkAlex, 2016-10-31
@MonkAlex

Use OfType, then the search will only be on the heirs of a certain type.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question