【问题标题】:PHP equivalent of uniqid() in C#PHP 相当于 C# 中的 uniqid()
【发布时间】:2015-02-07 15:17:49
【问题描述】:

试图在 C# 中复制一些 PHP 代码。 PHP 代码使用 uniqid 函数,将 more entropy 参数设置为 true。知道如何在 C# 中最好地复制它吗?

http://us2.php.net/uniqid

【问题讨论】:

  • 这是否类似于 .NET 术语中的 GUID?

标签: c# php


【解决方案1】:

经过一番谷歌搜索,我发现了 PHP 的 uniqid 是如何工作的,并在 c# 中实现了它:

private string GetUniqID()
{
    var ts = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0));
    double t = ts.TotalMilliseconds / 1000;

    int a = (int)Math.Floor(t);
    int b = (int)((t - Math.Floor(t)) * 1000000);

    return a.ToString("x8") + b.ToString("x5");
}

这段代码提供了完全相同的结果,唯一的区别是没有实现 uniqid() 的额外参数。

【讨论】:

    【解决方案2】:

    类似:

    string uniqid(string prefix, bool more_entropy) {
        if(string.IsNullOrEmpty(prefix)) 
          prefix = string.Empty;
    
        if (!more_entropy) {
          return (prefix + System.Guid.NewGuid().ToString()).Left(13);
        } else {
          return (prefix + System.Guid.NewGuid().ToString() + System.Guid.NewGuid().ToString()).Left(23);
        }
     }
    

    编辑:反映 cmets

    这是一个非常简单的我想不到的解决方案,我建议对于更严格的解决方案,您应该研究适当的“随机”数生成,例如通过 System.数学命名空间直接。请参阅这些其他SO questions and answers on random number generation

    System.Guid.NewGuid().ToString()

    会给你一个唯一的字符串。

    【讨论】:

    • 非常感谢 - 我就是这么想的,但我想确定一下。
    • 请记住,只有整个 Guid 应该是几乎肯定是唯一的。对于其字符串表示的一部分来说,这不一定是正确的。见blogs.msdn.com/oldnewthing/archive/2008/06/27/8659071.aspx
    • String.Left() 在 C# 中是 String.Substring()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-26
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多