扩展方法和通用约束的问题
我有一个基本接口和几个inheritance的接口。 基本接口有扩展方法,用于修改对象并返回基类的新实例( IChildA.Touch() => IBase
, IBase.Touch() => IBase
)。
对于一个inheritance路径( IChildB
和后代),我想实现返回与调用对象相同类型的对象的扩展方法( IGrandChildB.Touch() => IGrandChild
)。 为此,我想指定一个受限于IChildB
后代的通用扩展方法。
这工作到目前为止,但现在编译器无法解析来自IChildA
的调用。 它尝试使用IChildB
路径的扩展方法,而不是使用IBase
接口的扩展方法。 有没有一种优雅的方法来解决这个问题?
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(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(); } }
我不知道你的具体用例,但是如果删除非generics方法并将generics方法约束为IBase,则该示例仍将编译。
上述就是C#学习教程:扩展方法和通用约束的问题分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public interface IBase {} public interface IChildA : IBase {} public interface IChildB : IBase {} public static class BaseExtensions { public static T Touch(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(); } }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/959649.html