如何创建可包含Real或String的数据类型? [英] How Do I create a data type that can contain either Real or String?

查看:177
本文介绍了如何创建可包含Real或String的数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建像System.TVariant这样的东西。我不能使用TVariant,因为它将数据存储在它认为应该是的类型中,即它将存储少于Real的另一种类型的数字......无论如何,如果有解决方法,我不会想要这样,我只是想知道它是如何工作的以及如何创建一个可以容纳不同数据类型的数据类型,如下所示:

I'm trying to create something like System.TVariant. I can't use TVariant because it stores the data in a type which it thinks it should be, i.e it will store a small number in another type than Real... Anyways, if there is a workaround for that, I don't want that, I just want to know 'how' it works and how I can create a data type that can hold varying data types, Something like this:

type
  TStrInt = (AnsiString or Integer);

var
  TVr: TStrInt;

begin
  TVr := 56;
  WriteLn(TVr);
end.



如您所见,'或'给出了错误,所以'TVr:= 56'。无论如何要做到这一点?


As you can see, the 'or' gives error, and so does 'TVr := 56'. Anyway to do this?

推荐答案

我想你必须使用变种记录,例如见< a href =http://www.delphibasics.co.uk/Article.asp?Name=Records>将数据组存储在一起 [ ^ ]。
I guess you have to use a Variant Record, see, for instance "Storing groups of data together"[^].


听取一个友好的建议:永远不要曾经使用Variants,除非某些第三方跛脚API需要它们。这种类型的虚构好处是一种非常普遍的错觉,会损害部分开发人员。 Delphi和许多其他技术都面向强类型 https://en.wikipedia.org/wiki/ Strong_and_weak_typing [ ^ ]。



不要误会我的意思,不同的打字范例,例如松散打字,可以非常高效,特别是在某些脚本(解释性)语言,但相信我,大多数此类技术比蹩脚的COM变体更好。此外,COM严重过时,没有理由遵循其最严重的缺点。



-SA
Listen for a good friendly advice: never ever use Variants, unless they are required by some 3rd-party lame API. Imaginary benefits of this type is a pretty usual delusion which damages part of developers. Delphi and many other technologies are oriented to strong typing, https://en.wikipedia.org/wiki/Strong_and_weak_typing[^].

Don't get me wrong, different typing paradigms, such as loose typing, can be extremely productive, especially in some scripting (interpretive) languages, but trust me, most of such technologies are way better than the lame COM variants. Also, COM is badly obsolete, there is no a reason to follow its worst drawbacks.

—SA

这篇关于如何创建可包含Real或String的数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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