简体   繁体   English

为GUID定义增量运算符

[英]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... 但是,它带有一些免责声明...

  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; 实际上,这实际上并没有将增量运算符添加到Guid定义本身。 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是密封结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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