在实现接口的非泛型方法中对泛型进行模式匹配 [英] Pattern matching on generics in a non-generic method implementing an interface

查看:57
本文介绍了在实现接口的非泛型方法中对泛型进行模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个令人沮丧的问题.我正在ASP.NET MVC中构建一个视图引擎,并且正在实现IViewEngine接口.在一种方法中,我试图动态找出视图结果的类型.有时结果是一个模板(类型为Template<'key>).键用于定位模板中的占位符,其思想是使用区分的联合,每个网站可能唯一.看起来可能像这样:

I have a frustrating problem. I'm building a view engine in ASP.NET MVC and are implementing the interface IViewEngine. In one of the methods I'm trying to dynamically figure out the type of the result of a view. Sometimes the result is a template (with the type Template<'key>). The keys are used to target a placeholder in the template, and the idea is to use a discriminated union, potentially unique for each web site. It could look like this:

type MasterKey = | HeadContent | HeaderContent | MainContent | FooterContent
let MasterTemplate : Template<MasterKeys> = ...

现在,问题是这样的:由于我正在实现接口,因此我无法控制方法签名.由于我无法添加泛型类型参数,因此'a将被转换为obj,并且模板将不会与以下内容匹配:

Now, the problem is this: since I'm implementing an interface, I have no control over the method signature. Since I can not add a generic type parameter, the 'a will be converted to an obj and the Template will not be a match below:

   match result with
   | :? foo -> ...
   | :? bar -> ...
   | :? Template<'a> -> ...

有什么想法吗?

推荐答案

是否可以根据使用的'key 的类型,使整个视图引擎类通用?各个项目将需要从您的视图引擎类继承,并在流程中指定键的类型.

Can you make the whole view engine class generic, according to the type of 'key it uses? Indivudual projects will need to inherit from your view engine class and specify the type of key in the process.

这篇关于在实现接口的非泛型方法中对泛型进行模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆