按需跳过通用参数 [英] skip generic parameter on demand

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

问题描述

  TVertex< T>< p> = class 
public
名称:String;
OutputAttributes:TVertexOutputAttributes;
标记:布尔型;
数据:T; //用户定义的数据属性
函数HasAdditionalAttributes:Boolean;
构造函数Create();
程序标记;
程序UnMark;
end;

使用以下代码行创建TVertex类的单个实例:

  A:= TVertex< Integer> .Create(); 
A.Name:='A';

在本例中,我们将T定义为整型数据类型。我的问题现在如下所示:



如果我的用例不需要任何assigend数据类型T,那么如果我可以跳过数据类型的规范,它会好得多/合乎逻辑。我失败了:

  A:= TVertex<> .Create(); 
A.Name:='A';

在创建过程中避免切换数据类型的任何更改???

解决方案

你明确要求的是有一个明显的缺陷。编译器会如何处理这个声明?

  Data:T; //用户定义的数据属性

如果您不提供 T ,那么编译器不知道该怎么做。

这个观察结果让我们有一种可能的方法。如果你不想提供 T ,那么可能你不希望这个类包含这个成员。如果它的类型不提供,它如何包含该成员?所以定义一个非泛型的版本:

  type 
TVertex = class
public
Name :String;
OutputAttributes:TVertexOutputAttributes;
标记:布尔型;
end;

然后从这个派生出您的通用版本:

 键入
TVertex< T> = class(TVertex)
public
Data:T; //用户定义的数据属性
end;

显然,您需要确定应该在哪个类中声明和实现方法。显然,任何不依赖于 Data 的方法都可以在非泛型类中实现。


I found this definition of an generic class in the web :

  TVertex<T> = class
  public
    Name: String;
    OutputAttributes: TVertexOutputAttributes;
    Marker: Boolean;
    Data: T; // User-defined data attribute
    function HasAdditionalAttributes: Boolean;
    constructor Create();
    procedure Mark;
    procedure UnMark;
  end;

a single instance of a TVertex class is created with the following line of code :

  A := TVertex<Integer>.Create();
  A.Name := 'A';

in this example we define T as Integer data Type. My question goes now like this :

If my use case does not need any assigend datatype T it would be much better / logical if I can skip the specification on the datatype. I failed with :

   A := TVertex<>.Create();
  A.Name := 'A';

Any change to avoid the handover of the datatype at the create process ???

解决方案

What you are explicitly asking for has one obvious flaw. What will the compiler do with this declaration?

Data: T; // User-defined data attribute

If you don't supply a T, then the compiler doesn't know what to do.

This observation leads us to one possible approach. If you don't want to supply T then presumably you don't want the class to contain this member. How can it contain that member if its type is not supplied? So define a non-generic version:

type
  TVertex = class
  public
    Name: String;
    OutputAttributes: TVertexOutputAttributes;
    Marker: Boolean;
  end;

And then derive your generic version from this:

type
  TVertex<T> = class(TVertex)
  public
    Data: T; // User-defined data attribute
  end;

Clearly you would need to determine in which class the methods should be declared and implemented. Clearly any methods that did not rely on Data could be implemented in the non-generic class.

这篇关于按需跳过通用参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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