TypeScript GUID 类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26501688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
A TypeScript GUID class?
提问by Gustav
Does anyone know of a good, solid, implementation of C# like GUID (UUID) in TypeScript?
有谁知道 TypeScript 中像 GUID (UUID) 这样的 C# 的良好、可靠的实现?
Could do it myself but figured I'd spare my time if someone else done it before.
可以自己做,但我想如果其他人以前做过,我会腾出时间。
回答by Fenton
There is an implementation in my TypeScript utilitiesbased on JavaScript GUID generators.
我的TypeScript 实用程序中有一个基于 JavaScript GUID 生成器的实现。
Here is the code:
这是代码:
class Guid {
static newGuid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
}
// Example of a bunch of GUIDs
for (var i = 0; i < 100; i++) {
var id = Guid.newGuid();
console.log(id);
}
Please note the following:
请注意以下事项:
C# GUIDs are guaranteed to be unique. This solution is very likelyto be unique. There is a huge gap between "very likely" and "guaranteed" and you don't want to fall through this gap.
C# GUID 保证是唯一的。这个解决方案很可能是独一无二的。“很可能”和“保证”之间存在巨大的差距,您不想掉入这个差距。
JavaScript-generated GUIDs are great to use as a temporary key that you use while waiting for a server to respond, but I wouldn't necessarily trust them as the primary key in a database. If you are going to rely on a JavaScript-generated GUID, I would be tempted to check a register each time a GUID is created to ensure you haven't got a duplicate (an issue that has come up in the Chrome browser in some cases).
JavaScript 生成的 GUID 非常适合用作等待服务器响应时使用的临时键,但我不一定相信它们是数据库中的主键。如果您打算依赖 JavaScript 生成的 GUID,我很想在每次创建 GUID 时检查寄存器以确保您没有重复(在某些情况下,Chrome 浏览器中会出现这个问题) )。
回答by dburmeister
I found this https://typescriptbcl.codeplex.com/SourceControl/latest
我发现这个https://typescriptbcl.codeplex.com/SourceControl/latest
here is the Guid versionthey have in case the link does not work later.
这是他们拥有的 Guid 版本,以防链接稍后失效。
module System {
export class Guid {
constructor (public guid: string) {
this._guid = guid;
}
private _guid: string;
public ToString(): string {
return this.guid;
}
// Static member
static MakeNew(): Guid {
var result: string;
var i: string;
var j: number;
result = "";
for (j = 0; j < 32; j++) {
if (j == 8 || j == 12 || j == 16 || j == 20)
result = result + '-';
i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
result = result + i;
}
return new Guid(result);
}
}
}