是否有一个合理的方式,以“默认”类型参数在C#泛型?
-
22-08-2019 - |
题
在C ++模板,一个可以指定某种类型的参数是一个缺省值。即除非明确指定,它将使用类型T.
可以这样做或C#近似?
我在寻找类似:
public class MyTemplate<T1, T2=string> {}
所以该类型的一个实例,不明确指定T2
:
MyTemplate<int> t = new MyTemplate<int>();
将基本上是:
MyTemplate<int, string> t = new MyTemplate<int, string>();
最终我在看的情况下,其中存在被相当广泛地使用的模板,但我考虑与另外的类型参数扩大。我可以继承,我想,但我很好奇,如果有这一脉的其他选项。
解决方案
子类是最好的选择。
我会继承你的主要泛型类:
class BaseGeneric<T,U>
与特定的类
class MyGeneric<T> : BaseGeneric<T, string>
此可以很容易地保持你的逻辑在一个地方(基类),也容易以提供使用选项。根据不同的类,有要做到这一点可能需要很少的额外工作。
其他提示
一种解决方案是子类。另一个我会转而使用,是工厂方法(结合var关键字)。
public class MyTemplate<T1,T2>
{
public MyTemplate(..args..) { ... } // constructor
}
public static class MyTemplate{
public static MyTemplate<T1,T2> Create<T1,T2>(..args..)
{
return new MyTemplate<T1, T2>(... params ...);
}
public static MyTemplate<T1, string> Create<T1>(...args...)
{
return new MyTemplate<T1, string>(... params ...);
}
}
var val1 = MyTemplate.Create<int,decimal>();
var val2 = MyTemplate.Create<int>();
在上面的例子中是val2
类型MyTemplate<int,string>
的而非强>从它派生类型。
A型class MyStringTemplate<T>:MyTemplate<T,string>
是不相同的类型MyTemplate<T,string>
。
这可能造成在某些情况下一些问题。
例如,你不能施放MyTemplate<T,string>
的实例,以MyStringTemplate<T>
。
还可以创建一类过载像这样
public class MyTemplate<T1, T2> {
public T1 Prop1 { get; set; }
public T2 Prop2 { get; set; }
}
public class MyTemplate<T1> : MyTemplate<T1, string>{}
C#不支持这样的功能。
正如你所说,你可以继承它(如果它不密闭,复制所有构造函数声明),但它是一个完全不同的事情。
不幸的是C#不支持你正在尝试做的。这将是为了实现给定的,对于一个参数的默认类型必须坚持以通用的约束和最有可能创造头疼当CLR努力确保类型安全困难的特点。
不隶属于 StackOverflow