在C#中,可以使用委托、事件或异步方法来实现方法的懒加载。下面是使用这三种方法的示例:
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}");
}
}
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.");
}
}
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#中实现方法的懒加载。你可以根据具体需求选择合适的方法。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。