简体   繁体   中英

Defining Increment Operator for GUID

I need to incrementally increase GUID, which I successfully achieved using this

But now, I want to make it through the Increment operator ++ because I want my code to look pretty and concise .

My code:

public class GuidOps
{
    public static Guid operator ++(Guid input)
    {
        return input.Increment(); //Increment works as intended here
    }
}

That doesn't work because the type required for the ++ operator must the type of the class where the operator is declared.

在此处输入图片说明

Obviously I cannot override declaration of GUID itself

Do you think it is possible to define ++ on GUIDs ?

Because Guid is sealed, the only way to do something even remotely close to this is to create a wrapper which in turn updates a Guid property on the wrapper. However, it comes with a few disclaimers...

  1. This is terribly confusing and dumb. Don't do it. Nothing about this behavior is expected or reasonable. It will lead to maintainability issues
  2. This still doesn't actually add the incrementor operator to the Guid definition itself; it only adds the operator to the wrapper. Now we've added abstraction for abstraction's sake and solved nothing. The code is less readable.

That said, the following will get you close to at least overriding the operator and to point out the issues that arise from trying to make code too clever:

public class GuidWrapper
{
    public Guid GuidInstance { get; set; } = Guid.NewGuid();

    public static GuidWrapper operator ++(GuidWrapper input)
    {
        input.GuidInstance = input.GuidInstance.Increment();
        return input;
    }
}

var wrapper = new GuidWrapper();
var guid = wrapper.GuidInstance;
var guid2 = wrapper++.GuidInstance;

这是不可能做到的,因为GUID是密封结构

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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