温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎样在C#中实现方法的懒加载

发布时间:2024-12-13 18:16:45 来源:亿速云 阅读:79 作者:小樊 栏目:编程语言

在C#中,可以使用委托、事件或异步方法来实现方法的懒加载。下面是使用这三种方法的示例:

  1. 使用委托:
using System;

public class LazyMethod
{
    private readonly Func<object, object> _lazyMethod;
    private object _result;

    public LazyMethod(Func<object, object> lazyMethod)
    {
        _lazyMethod = lazyMethod;
    }

    public object Execute(object input)
    {
        if (_result == null)
        {
            _result = _lazyMethod(input);
        }

        return _result;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var lazyMethod = new LazyMethod(x =>
        {
            Console.WriteLine("Method is being executed.");
            return x * 2;
        });

        var result = lazyMethod.Execute(5);
        Console.WriteLine($"Result: {result}");
    }
}
  1. 使用事件:
using System;

public class LazyMethod
{
    private readonly EventHandler _eventHandler;
    private bool _isExecuted = false;

    public LazyMethod(EventHandler eventHandler)
    {
        _eventHandler = eventHandler;
    }

    public void Execute()
    {
        if (!_isExecuted)
        {
            _eventHandler?.Invoke(this, EventArgs.Empty);
            _isExecuted = true;
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        var lazyMethod = new LazyMethod(x =>
        {
            Console.WriteLine("Method is being executed.");
            return x * 2;
        });

        lazyMethod.Execute();
        Console.WriteLine("Result: Method executed.");
    }
}
  1. 使用异步方法:
using System;
using System.Threading.Tasks;

public class LazyMethod
{
    private readonly Func<Task<object>> _asyncLazyMethod;
    private Task<object> _task;

    public LazyMethod(Func<Task<object>> asyncLazyMethod)
    {
        _asyncLazyMethod = asyncLazyMethod;
    }

    public async Task<object> ExecuteAsync()
    {
        if (_task == null)
        {
            _task = _asyncLazyMethod();
            await _task;
        }

        return _task.Result;
    }
}

class Program
{
    static async Task Main(string[] args)
    {
        var lazyMethod = new LazyMethod(async () =>
        {
            Console.WriteLine("Method is being executed.");
            await Task.Delay(1000);
            return "Result";
        });

        var result = await lazyMethod.ExecuteAsync();
        Console.WriteLine($"Result: {result}");
    }
}

这些示例展示了如何在C#中实现方法的懒加载。你可以根据具体需求选择合适的方法。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI