【发布时间】:2020-05-01 08:06:37
【问题描述】:
我正在尝试编写IThingRequest<TEntity> 的扩展方法,它返回Thing<TEntity>。我希望该方法只返回 TEntity 的底层类型,而不是它会实现的任何其他泛型类或接口。因此,在下面的示例中,希望返回类型应该是 Thing<Entity> 而不是 Thing<GenericClass<Entity>>。
扩展方法:
public static Thing<TEntity> DoStuff<TEntity>(IThingRequest<TEntity> request)
=> new Thing<TEntity>();
调用扩展方法:
public class Request : IThingRequest<GenericClass<Entity>>
{ }
var request = new Request();
var result = request.DoStuff();
结果类型现在是Thing<GenericClass<Entity>>。
我的第一反应是where 有办法实现这一点,但我想不通。我也考虑过使用反射来获取TEntity 的非泛型类型并返回Thing<object>,但我认为这需要在使用DoStuff 方法的地方进行转换。
非常感谢任何帮助!
【问题讨论】:
-
传入泛型类时为什么要返回非泛型类?您能否展示一些具有某些上下文的示例代码,以便帮助人们理解内容和原因?我在某种程度上明白你的要求,但你想用这个解决什么,也许有更好的模式?
-
return语句在表达式体方法中不需要,请发布您的实际代码,当前不会编译 -
谢谢,错过了,删除了退货!
-
你说得对@Charleh,我在想这个错误,而不是让
Request实现IThingRequest<GenericClass<Entity>>我改为分别实现GenericClass<Entity>, IThingRequest<Entity>。
标签: c# generics extension-methods