zoukankan      html  css  js  c++  java
  • 通过ref返回解决C# struct结构体链式调用的问题

    通常结构体不能进行链式调用,因为返回值是一个新的值,需要赋回原值。但现在通过ref关键字配合扩展方法,也能进行链式调用了。

    结构体:

    public struct Foo
    {
        public int a;
    
    
        public Foo AddOne()
        {
            a++;
    
            return this;
        }
    
        public Foo AddTwo()
        {
            a += 2;
    
            return this;
        }
    }

    执行测试:

    Foo foo = new Foo();
    foo
        .AddOne()
        .AddTwo();
    
    Debug.Log(foo.a);//1(错误)

    那么借助c#新的ref关键字,我们可以引用返回结构:

    public ref Foo AddOne()
    {
        a++;
    
        return ref this;/*ref不能返回this*/
    }

    但是编译器不能通过,没关系,可以通过扩展方法实现。

    扩展方法实现ref返回:

    结构:

    public struct Foo
    {
        public int a;
    
    
        public void AddOne()
        {
            a++;
        }
    
        public void AddTwo()
        {
            a += 2;
        }
    }

    扩展方法:

    public static class FooExtensions
    {
        public static ref Foo AddOneRef(this ref Foo foo)
        {
            foo.AddOne();
            return ref foo;
        }
        
        public static ref Foo AddTwoRef(this ref Foo foo)
        {
            foo.AddTwo();
            return ref foo;
        }
    }

    调用测试:

    Foo foo = new Foo();
    foo
        .AddOneRef()
        .AddTwoRef();
    
    Debug.Log(foo.a); //3

    可见,结果正确。并且使用ref,函数返回时不会创建新的结构体。

  • 相关阅读:
    软件工程第八周总结
    一维最大子数组的和续
    程序员修炼之道阅读笔记02
    软件工程第七周总结
    团队软件的NABCD—校园知网
    程序员修炼之道阅读笔记01
    软件项目管理阅读笔记01
    个人作业4 结对开发地铁
    学习进度五
    学习进度四
  • 原文地址:https://www.cnblogs.com/hont/p/15530705.html
Copyright © 2011-2022 走看看