问题
I'm new to C#.
I know in vb.net, i can do this:
Dim guid as string = System.Guid.NewGuid.ToString
In C#, I'm trying to do
String guid = System.Guid.NewGuid().ToString;
but i get an "Cannot convert method group 'ToString' to non-delegate type 'string'. Did you intend to invoke the method?" error.
回答1:
You're missing the ()
after ToString
that marks it as a function call vs. a function reference (the kind you pass to delegates), which incidentally is why c# has no AddressOf
operator, it's implied by how you type it.
Try this:
string guid = System.Guid.NewGuid().ToString();
回答2:
According to MSDN the method Guid.ToString(string format)
returns a string representation of the value of this Guid instance, according to the provided format specifier.
Examples:
guidVal.ToString()
orguidVal.ToString("D")
returns 32 digits separated by hyphens:00000000-0000-0000-0000-000000000000
guidVal.ToString("N")
returns 32 digits:00000000000000000000000000000000
guidVal.ToString("B")
returns 32 digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
回答3:
In Visual Basic, you can call a parameterless method without the braces (()
). In C#, they're mandatory. So you should write:
String guid = System.Guid.NewGuid().ToString();
Without the braces, you're assigning the method itself (instead of its result) to the variable guid
, and obviously the method cannot be converted to a String
, hence the error.
回答4:
String guid = System.Guid.NewGuid().ToString();
Otherwise it's a delegate.
回答5:
Here are examples of output from each of the format specifiers:
N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}
The default is D
.
Run this yourself.
回答6:
you are missing () on the end of ToString.
回答7:
You need
String guid = System.Guid.NewGuid().ToString();
回答8:
Did you write
String guid = System.Guid.NewGuid().ToString;
or
String guid = System.Guid.NewGuid().ToString();
notice the paranthesis
回答9:
Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens
来源:https://stackoverflow.com/questions/1700361/how-to-convert-a-guid-to-a-string-in-c