Reputation: 1379
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.
Upvotes: 1
Views: 73
Reputation: 5103
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());
}
Upvotes: 0
Reputation: 888167
You're looking for generic constraints:
public T GetClosest<T>(List<T> list) where T : BaseClass {
Upvotes: 2