简体   繁体   English

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

[英]How can I cast a System.Guid to a string in C#

I have the following field definition in a class: 我在一个类中有以下字段定义:

   public Nullable<System.Guid> GlobalId { get; set; }

I have another class with the following: 我还有另外一门课程,其中包括:

   public string GlobalId { get; set; }

I would like to put the value of from the field with type System.Guid into the string. 我想将类型为System.Guid的字段的值放入字符串中。

I tried to do this here: 我在这里尝试这样做:

        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;

But it's giving me an error saying: 但这给了我一个错误:

   Cannot convert type 'System.Guid?' to 'string'

Can someone tell me how I could do this? 有人可以告诉我我该怎么做吗?

You can get the string representation of the GUID by calling ToString() on it. 您可以通过在GUID上调用ToString()来获取它的字符串表示形式。

As your GUID is nullable, check if it's null before calling ToString() : 由于您的GUID可为空,因此在调用ToString()之前检查它是否为空:

string myString = guid.HasValue ? guid.Value.ToString() : "default string value";

You don't cast to string. 您不会强制转换为字符串。 You use ToString() method. 您使用ToString()方法。

Like this: 像这样:

GlobalId = m.GlobalId.ToString()

You can convert a Guid with .ToString(): 您可以使用.ToString()转换Guid:

Guid gid = Guid.NewGuid();

string myID = gid.ToString();

Or using 或使用

Convert.ToString

Like: 喜欢:

Guid gid = Guid.NewGuid();

string myID = Convert.ToString(gid);

使用Convert.ToString而不是(string)

GlobalId =  Convert.ToString(m.GlobalId)
GlobalId = m.GlobalId.ToString()

Just use ToString() method 只需使用ToString()方法

Guid? g = null;    
string s = g.ToString();

in case of null it will return String.Empty otherwise you'll get string representation of your Guid 如果为null ,它将返回String.Empty否则您将获得Guid字符串表示形式

string Id = Guid.NewGuid().ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM