实例化通用类型 [英] Instantiating a Generic Type

查看:64
本文介绍了实例化通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个概念很明显,它不是直截了当的,所以我想我会问第一个是否可能,第二个好主意。  

This concept has become obvious that it is not straight forward, so I figured I would ask if it is first possible, second a good idea.  

这是概念。  我有一个基本模型类,我试图将所有标准函数放入,例如,调用Web API,读取文件等等...每个Model Class都有一个实例化函数,它返回一个实例化的
特定模型的对象。  例如:

Here is the concept.  I have a Base Model Class that I am trying to get all the standard functions into, for example, call Web APIs, reading files, etc... One thing that every Model Class has is an instantiation function that returns an instantiated object of the specific model.  So for example:

public myModel : ModelBase
{
  //... Model Specific Stuff Here

  public static myModel Instantiate()
  {
      return new myModel();
  }
}

我想要做的是将此实例化函数移动到模型库中并考虑这样做:

What I would like to do is move this Instantiate function into the Model Base and was thinking about doing this:

public ModelBase<T>
{
  //... Model Base Stuff Here

  public static T Instantiate()
  {
      return new T();
  }
}

由于我发现的各种原因,这是不可能的。  我已经看到你可以在哪里实例化一个泛型类型的列表,但是只是一个简单的泛型类型呢?

For the various reasons that I have found out, this is not possible.  I have seen where you can instantiate a list of a generic type, but what about just a simple generic type?

推荐答案

你需要一个约束来告诉编译器T是'newable'。

You would need a constraint to tell the compiler that T is 'newable'.

查看泛型约束
here

换句话说:

public ModelBase<T> where T: new()

可能需要进一步的约束,具体取决于你计划对班级内的T变量做什么。

Further constraints may be required, depending on what you plan on doing to your T variable inside the class.

(另外,另外,当我读到你的句子时,警告铃声响起,说明你希望你的基础模型类有"所有标准功能,例如Web API,读取文件等"。警告关于将多少功能
放入一个单一的类中,因为你冒险陷入反模式:尝试并遵循
SOLID
原则,特别是说一个类应该具有"单一责任",即应该只对一件事负责!)

(Also, as an aside, warning bells rang in my head when I read your sentence saying how you want your Base Model class to have "all standard functions into, for example Web APIs, reading files, etc". Be warned about putting too much functionality into a single monolithic class as you risk falling into an anti-pattern: Try and follow the SOLID principles, specifically the bit that says that a class should have "single responsibility", i.e. should be responsible for one thing only!)


这篇关于实例化通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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