简体   繁体   English

如何选择从泛型方法调用的正确的 c# 重载扩展方法

[英]How to pick the correct c# overloaded extension method called from a generic method

I am struggling to get the correct extension methods called in generic methods.我正在努力获得通用方法中调用的正确扩展方法。

I guess it is a limitation of compile time method picking but is there a clever way around this in C#?我想这是编译时方法选择的限制,但在 C# 中是否有巧妙的方法来解决这个问题?

[TestClass]
public class WrongOverloadSelection 
{
    [TestMethod]
    public void WorksNew()
    {
        new Generic<A>().Test();
    }

    [TestMethod]
    public void FailsGeneric()
    {
        PicksWrongOverload<A>();
    }

    public void PicksWrongOverload<T>()
    {
        new Generic<T>().Test();
    }
}

public class A{}
public class Generic<T>{}

public static class Extensions
{
    public static void Test(this Generic<A> source) { }

    public static void Test<T>(this Generic<T> source) 
    {
        throw new Exception("Not this one!");
    }
}

Try this:尝试这个:

// Now it picks then right one
public static void PicksWrongOverload<T>()
{
    Extensions.Test((dynamic)new Generic<T>());
}

The reason for this is explained here , but essentially at runtime the CLR will convert the dynamic type to the required type of the routine, and if there is nothing happening that violates the type checking rules then you are good to go.原因在此处解释,但本质上在运行时 CLR 会将动态类型转换为例程所需的类型,如果没有发生任何违反类型检查规则的事情,那么您就可以开始了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM