代码之家  ›  专栏  ›  技术社区  ›  John

C中uniqid()的PHP等价物#

  •  2
  • John  · 技术社区  · 17 年前

    http://us2.php.net/uniqid

    2 回复  |  直到 17 年前
        1
  •  13
  •   Adorjan Princz    11 年前

    通过谷歌搜索,我发现了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
  •  8
  •   Community Mohan Dere    9 年前

    比如:

    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);
        }
     }
    

    编辑:反映评论

    这是一个非常简单的问题 从我的头顶上 SO questions and answers on random number generation .

    System.Guid.NewGuid().ToString()

    将给您一个唯一的字符串。