如何将System.Guid转换为C#中的字符串

Sam*_*tar 0 c#

我在类中有以下字段定义:

   public Nullable<System.Guid> GlobalId { get; set; }
Run Code Online (Sandbox Code Playgroud)

我有另一个课程如下:

   public string GlobalId { get; set; }
Run Code Online (Sandbox Code Playgroud)

我想将类型为System.Guid的字段的值放入字符串中.

我试着这样做:

        var questionIds = _questionsRepository.GetAll()
            .Where(m => m.Problem != null &&
            m.Problem.SubTopic != null &&
            m.Problem.SubTopic.Topic != null &&
            m.Problem.SubTopic.Topic.SubjectId == 1)
            .Select(m => new QuestionHeader { GlobalId = (string) m.GlobalId })
            .ToList();
        return questionIds;
Run Code Online (Sandbox Code Playgroud)

但它给了我一个错误说:

   Cannot convert type 'System.Guid?' to 'string'
Run Code Online (Sandbox Code Playgroud)

谁能告诉我怎么做到这一点?

ken*_*n2k 8

您可以通过调用来获取GUID的字符串表示形式ToString().

由于您的GUID可以为空,因此在调用之前检查它是否为null ToString():

string myString = guid.HasValue ? guid.Value.ToString() : "default string value";
Run Code Online (Sandbox Code Playgroud)

  • 根据http://stackoverflow.com/questions/2449008/nullable-tostring,您无需将无值表示为空字符串. (3认同)