简体   繁体   中英

How to pass a derived class to a base class function and return the derived class c#

I'm not sure if this is possible, but if it is not, what's the best/most elegant way to do this.

I have a List<DerivedClass> and I want to pull an element from the list that matches some criterion from it's BaseClass.

public class BaseClass {...}
public class DerivedClass : BaseClass {...}

List<DerivedClass> dcList = new List<DerivedClass>();
..
DerivedClass dc = GetTheOneWeWant(dcList)

where the function looks like this

public BaseClass GetTheOneWeWant(List<BaseClass> bc) {
  return bc[0]; //for example
}

So that that function can apply to all derived classes.

I tried something like this

    public T GetClosest<T>(List<T> list) {
        return list.Aggregate((c, d) => c.DistanceFrom(FrameCenterX, FrameCenterY) < d.DistanceFrom(FrameCenterX, FrameCenterY) ? c : d);
    }

but T doesn't know about method DistanceFrom(), and it will not let me cast T as a BaseClass. I'm not sure the best way to handle this. I could cast DerivedClass to BaseClass and send it to the function, but I want it to return the DerivedClass, not the BaseClass.

您正在寻找通用约束:

public T GetClosest<T>(List<T> list) where T : BaseClass {

Make the property/field/method you're using to determine if the "OneYouWant" public so that you can see it in derived class.

ex:

class Base {
    public bool MyProperty {get;set;}
}
class Derived : Base {

}
main.cs {
    var derivedList = //a List<Derived>()
    var whatIWanted = derivedList.Where(d => d.MyProperty);
}

Edit: Meant public

If you don't want to expose the property/field/method, then make that property protected and make a method that can get to it internally but perform the validation you need.

ex:

class Base {
    protected bool MyProperty {get;set;}
}
class Derived : Base {
    public bool IsWhatIWant() {
         return MyProperty;
    }
}
main.cs {
    var derivedList = //a List<Derived>()
    var whatIWanted = derivedList.Where(d => d.IsWhatIWant());
}

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