Problem with Extension Methods and Generic Constraints

这一生的挚爱 提交于 2019-12-07 16:14:19

问题


I have a base interface and several inherited interfaces. There are extension methods for the base interface that modify the object and return a new instance of the base class (IChildA.Touch() => IBase, IBase.Touch() => IBase).

For one inheritance path (IChildB and descendants) i want to implement extension methods that return an object of the same type as the calling object (IGrandChildB.Touch() => IGrandChild). For this i would like to specify a single generic extension method that is constrained to IChildB descendants.

This works so far, but now the compiler cannot resolve the call from IChildA. It tries to use the extension method for the IChildB path and fails instead of using the extension method for the IBase interface. Is there an elegant way to fix this?

public interface IBase {}

public interface IChildA : IBase {}

public interface IChildB : IBase {}

public static class BaseExtensions
{
  public static IBase Touch(this IBase self) { return self; }
  public static T Touch<T>(this T self) where T : IChildB { return self; }
}

public static class TestClass
{
  public static void Test()
  {
    IChildA a = null;
    IBase firstTry = a.Touch();  //Cannot resolve to BaseExtensions.DoSomething(this IBase obj)
    IBase secondTry = ((IBase)a).Touch();  //Resolves to BaseExtensions.DoSomething(this IBase obj)

    IChildB b = null;
    IChildB touchedB = b.Touch();
  }
}

回答1:


I don't know your concrete use-case, but the example will still compile if you drop the non-generic method and instead constrain the generic method to IBase.

public interface IBase {}

public interface IChildA : IBase {}

public interface IChildB : IBase {}

public static class BaseExtensions
{
    public static T Touch<T>(this T self) where T : IBase { return self; }
}

public static class TestClass
{
    public static void Test()
    {
        IChildA a = null;
        IBase firstTry = a.Touch();

        IChildB b = null;
        IChildB touchedB = b.Touch();
    }
}


来源:https://stackoverflow.com/questions/4003117/problem-with-extension-methods-and-generic-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!