Guid is all 0's (zeros)?

后端 未结 6 1194
忘掉有多难
忘掉有多难 2020-12-05 01:35

I\'m testing out some WCF services that send objects with Guids back and forth. In my web app test code, I\'m doing the following:

var responseObject = proxy         


        
相关标签:
6条回答
  • 2020-12-05 01:59

    Lessons to learn from this:

    1) Guid is a value type, not a reference type.

    2) Calling the default constructor new S() on any value type always gives you back the all-zero form of that value type, whatever it is. It is logically the same as default(S).

    0 讨论(0)
  • 2020-12-05 02:00

    Use the static method Guid.NewGuid() instead of calling the default constructor.

    var responseObject = proxy.CallService(new RequestObject
    {
        Data = "misc. data",
        Guid = Guid.NewGuid()
    });
    
    0 讨论(0)
  • 2020-12-05 02:02

    Try doing:

    Guid foo = Guid.NewGuid();
    
    0 讨论(0)
  • 2020-12-05 02:17

    Try this instead:

    var responseObject = proxy.CallService(new RequestObject
    {
        Data = "misc. data",
        Guid = new Guid.NewGuid()
    });
    

    This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

    When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

    Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
    Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
    Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
    Guid g4 = Guid.NewGuid();   // g4 is not all zeroes
    

    Compare this to doing the same thing with an int:

    int i1;                     // i1 is 0
    int i2 = new int();         // i2 is 0
    int i3 = default(int);      // i3 is 0
    
    0 讨论(0)
  • 2020-12-05 02:18

    Can't tell you how many times this has caught. me.

    Guid myGuid = Guid.NewGuid(); 
    
    0 讨论(0)
  • 2020-12-05 02:24

    In the spirit of being complete, the answers that instruct you to use Guid.NewGuid() are correct.

    In addressing your subsequent edit, you'll need to post the code for your RequestObject class. I'm suspecting that your guid property is not marked as a DataMember, and thus is not being serialized over the wire. Since default(Guid) is the same as new Guid() (i.e. all 0's), this would explain the behavior you're seeing.

    0 讨论(0)
提交回复
热议问题