[英]c# Dispatching Extension Methods based on Value not Reference
Given the following 2 extension methods鉴于以下2种扩展方法
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以及以下 2 次调用
//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?即使它的引用类型是对象但它的值类型是 EntityRestIdentityDescriber,我如何执行第二个扩展方法? I'm looking for static polymorphism.我正在寻找静态多态性。
try this尝试这个
public static string getIDPropertyName(this object entityIdentityDescriber)
{
if(entityIdentityDescriber is EntityRestIdentityDescriber<IDType>)
return entityIdentityDescriber.propertyNameDescribingID();
else
return "id";
}
You need double dispatch
.你需要double dispatch
。 Double dispatch
determine dispatch based on the actual type at runtime Double dispatch
根据运行时的实际类型确定调度
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
//......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.