[英]Defining Increment Operator for GUID
I need to incrementally increase GUID, which I successfully achieved using this 我需要逐步增加GUID,这是我用成功实现了这个
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 显然我不能覆盖GUID本身的声明
Do you think it is possible to define ++ on GUIDs ? 您认为可以在GUID上定义++吗?
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. 因为
Guid
是密封的,所以做某事甚至更接近此方法的唯一方法是创建一个包装器,该包装器反过来更新包装器上的Guid属性。 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是密封结构
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.