【问题标题】:How to pass a parameter to class constraint [duplicate]如何将参数传递给类约束[重复]
【发布时间】: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#


【解决方案1】:

试试

using (T entitiesContext = (T)Activator.CreateInstance(typeof(T), new[]{conn}))

【讨论】:

    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2014-12-27
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多