【发布时间】:2012-09-11 22:05:53
【问题描述】:
可能重复:
In there a generic constructor with parameter constraint in C#
我有这个动态传递对象类型的代码:
public static void Retion<T>() where T : DataContext, new()
{
using (T entitiesContext = new T())
{...}
我的问题是我需要一个带参数的构造函数,像这样:
public static void Retion<T>(String conn) where T : DataContext, new()
{
using (T entitiesContext = new T(conn))
{...}
当我尝试这个时,我得到一个错误:错误 137 'T':在创建变量类型的实例时无法提供参数。
【问题讨论】:
-
不能保证 T 的实际类型有一个带有这个签名的构造函数,即使 Datacontext 有它。这就是为什么在使用参数时不能使用约束的原因。
-
@SteveB 就此而言,不能保证实际类型也会有一个空的构造函数,但它由约束强制执行。我看不出有什么不同。此功能(OP 要求的)将非常方便
标签: c#