Reputation: 2006
Given the following 2 extension methods
public static string getIDPropertyName(this object value)
{
return "ID";
}
public static string getIDPropertyName<IDType>(this EntityRestIdentityDescriber<IDType> entityIdentityDescriber)
{
return entityIdentityDescriber.propertyNameDescribingID();
}
and the following 2 invocations
//arrange
object test = new CustomEntityRestModelIdentity();
//test.UserName = "KKK";
//act
var actual = test.getIDPropertyName(); //calls the first extension method
var actual2 = (test as CustomEntityRestModelIdentity).getIDPropertyName(); //calls the second extension method
How can I execute the second extension method even though its reference type is object but its value type is a EntityRestIdentityDescriber? I'm looking for static polymorphism.
Upvotes: 1
Views: 434
Reputation: 309
You need double dispatch
.Double dispatch
determine dispatch based on the actual type at runtime
public class IdPropertyNameResolver
{
public string GetIDPropertyName(object value)=>"ID";
public string GetIDPropertyName<T>(EntityRestIdentityDescriber<T> value)=>
value.propertyNameDescribingID();
}
//......do something
object o = new CustomEntityRestModelIdentity();
new IdPropertyNameResolver().GetIDPropertyName((dynamic)o);//CustomEntityRestModelIdentity id name
//......
Upvotes: 0
Reputation: 172
try this
public static string getIDPropertyName(this object entityIdentityDescriber)
{
if(entityIdentityDescriber is EntityRestIdentityDescriber<IDType>)
return entityIdentityDescriber.propertyNameDescribingID();
else
return "id";
}
Upvotes: 1