是否有合理的“违约"方法?C#泛型中的类型参数? [英] Is there a reasonable approach to "default" type parameters in C# Generics?

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

问题描述

在 C++ 模板中,可以指定某个类型参数是默认值.IE.除非明确指定,否则将使用类型 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#?

我正在寻找类似的东西:

I'm looking for something like:

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

这样一个没有显式指定T2的类型的实例:

So that an instance of the type that doesn't explicitly specify 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:

class BaseGeneric

具有特定的类

class MyGeneric: BaseGeneric

这使得将您的逻辑放在一个地方(基类)很容易,而且也很容易提供两种使用选项.根据课程的不同,实现这一目标可能只需要很少的额外工作.

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.

这篇关于是否有合理的“违约"方法?C#泛型中的类型参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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