The reason for this inference problem is that the general inference occurs at compile time and is thus identical to setting the desired type manually. If you switch to an explicit <Person> message with a call, does it cause an error at compile time?
One way is to make sure that the variable (note: NOT the Object!) You pass in explicitly refers to the Person class, as it seems in your code. Another way is to make general output happen at runtime using dyanmic :
GetProperty(this as dynamic, (prop) => prop.Name == "Name");
When clicking this as dynamic it calls GetProperty<dynamic> , using the exact type of this at runtime. The problem with this approach is that the dynamics are extremely slow compared to other objects.
If your models are strictly at the same level of inheritance, you can also use static polymorphism to handle the general parameter. Thusly:
public class BaseClass<TSelf> where TSelf : BaseClass<TSelf> public sealed class Model : BaseClass<Model>
That way you can use TSelf as a parameter instead of T , and that will be exactly correct. The problem with this approach is that it strictly limits you to one hierarchy with one inheritance, since everything that inherits from Model will return to the original problem and will be considered as Model , since it cannot override the used general parameter by its base class.
Assuming your GetProperty function does some reflection to check the property, you might consider passing a Type object instead of using a generic one and then typeof(T) , since .GetType() much more accurate.
David source share