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...
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.