如何约束泛型类型到必须有一个construtor这需要一定的参数? [英] How to constrain generic type to must have a construtor that takes certain parameters?

查看:133
本文介绍了如何约束泛型类型到必须有一个construtor这需要一定的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有打算与一组类型中使用的包装通用类。这些类型由工具生成,并都从基类派生ClientBase。虽然ClientBase只有一个默认的构造函数生成的所有类型有默认的构造函数,以及一个构造函数采用一个字符串作为参数。在包装类的构造函数中,我实例化,需要一个字符串构造函数的类型的实例。下面是一个示例代码:

I have a wrapper generic class that intended to be used with a set of types. Those types are generated by a utility and are all derived from a base class ClientBase. While ClientBase has only a default constructor, all generated types have default constructor as well as a constructor takes a string as parameter. In the constructor of the wrapper class, I instantiate an instance of the type with the constructor that takes a string. Here is a sample code:

public class ClientBase
{ }

public class GenericProxy<T>
    where T: ClientBase, new()
{
    T _proxy;

    public GenericProxy(string configName)
    {
        _proxy = new T(configName);    
    }
}

这代码不能编译,因为类型T不能保证有一个构造函数的字符串。有没有一种方法来定义的通用类约束强制执行的类型T必须有一个构造函数,一个字符串?如果这是不可能的,有什么很好的替代品来处理这种情况?

This code does not compile because type T is not guaranteed to have a constructor that takes a string. Is there a way to define a constrain on the generic class to enforce that the type T must have a constructor that take a string? If this is not possible, what are good alternatives to handle this kind of situation?

推荐答案

这是不可能的。我想看到的静态接口以处理这个问题,但别指望他们很快就随时...

It's not possible. I'd like to see "static interfaces" to handle this, but don't expect them any time soon...

替代:


  • 指定一个委托充当工厂对于T

  • 指定另一个接口作为一个工厂对于T

  • 指定初始化对T本身的接口(和添加约束,使 T 实现的接口)

  • Specify a delegate to act as a factory for T
  • Specify another interface to act as a factory for T
  • Specify an interface on T itself for initialization (and add a constraint so that T implements the interface)

前两个是真的等价的。基本上你想你的代理类改变这样的:

The first two are really equivalent. Basically you'd change your proxy class to something like this:

public class GenericProxy<T>
    where T: ClientBase, new()
{
    string _configName;
    T _proxy;
    Func<string, T> _factory;

    public GenericProxy(Func<string, T> factory, string configName)
    {
        _configName = configName;
        _factory = factory;
        RefreshProxy();
    }

    void RefreshProxy() // As an example; suppose we need to do this later too
    {
        _proxy = factory(configName);
    }
}



(我假设你将要创建更多的实例后 - 否则你还不如通过T的实例到构造函数)

(I assume you're going to want to create more instances later - otherwise you might as well pass an instance of T into the constructor.)

这篇关于如何约束泛型类型到必须有一个construtor这需要一定的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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