c#基于Value not Reference的调度扩展方法

时间:2017-03-01 08:38:33

标签: c# polymorphism extension-methods static-polymorphism

给出以下2种扩展方法

public static string getIDPropertyName(this object value)
{
    return "ID";
}

public static string getIDPropertyName<IDType>(this EntityRestIdentityDescriber<IDType> entityIdentityDescriber)
{
    return entityIdentityDescriber.propertyNameDescribingID();
}

以及以下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

即使其引用类型是object但其值类型是EntityRestIdentityDescriber,我如何执行第二个扩展方法?我正在寻找静态多态性。

2 个答案:

答案 0 :(得分:1)

试试这个

public static string getIDPropertyName(this object entityIdentityDescriber)
{
    if(entityIdentityDescriber is EntityRestIdentityDescriber<IDType>)
        return entityIdentityDescriber.propertyNameDescribingID();
    else
        return "id";
}

答案 1 :(得分:0)

您需要double dispatchDouble 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
//......