是否有一个合理的方法来"默认"键入C#泛型参数? [英] Is there a reasonable approach to "default" type parameters in C# Generics?

查看:97
本文介绍了是否有一个合理的方法来"默认"键入C#泛型参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++模板,可以指定某种类型的参数是默认。即除非明确指定,它将使用T类型

In C++ templates, one can specify that a certain type parameter is a default. I.e. unless explicitly specified, it will use type T.

可以这样做,或在C#中近似?

Can this be done or approximated in C#?

我在寻找类似:

public class MyTemplate<T1, T2=string> {}

所以该类型的实例没有明确指定 T2

MyTemplate<int> t = new MyTemplate<int>();

将基本上是:

MyTemplate<int, string> t = new MyTemplate<int, string>();

最后我在看一个案例,其中有是相当广泛的一种模板,但我正在考虑一个额外的类型参数扩大。我可以继承,我想,但我很好奇,如果有这一脉的其他选项。

Ultimately I am looking at a case wherein there is a template that is fairly widely used, but I am considering expanding with an additional type parameter. I could subclass, I guess, but I was curious if there were other options in this vein.

推荐答案

子类化是最好的选择。

我会继承你的主要泛型类:

I would subclass your main generic class:

类BaseGeneric&LT; T,U&GT;

与特定的类

类MyGeneric&LT; T&GT; :BaseGeneric&LT; T,串&GT;

这很容易让你的逻辑在一个地方(基类),但也容易同时提供使用选项。根据不同的类,还有就是实现这一目标可能需要非常少的额外工作。

This makes it easy to keep your logic in one place (the base class), but also easy to provide both usage options. Depending on the class, there is probably very little extra work needed to make this happen.

这篇关于是否有一个合理的方法来&QUOT;默认&QUOT;键入C#泛型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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