首页 / C# / C#中的Guard对象
C#中的Guard对象
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#中的Guard对象,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1779字,纯文字阅读大概需要3分钟。
内容图文
![C#中的Guard对象](/upload/InfoBanner/zyjiaocheng/794/42527d49cce949b99a71c92530039ad8.jpg)
在C中,编写一个Guard类并相当容易引用变量(通常是bool),当实例对象退出作用域并被破坏时,析构函数会将变量重置为原始值.
void someFunction() {
if(!reentryGuard) {
BoolGuard(&reentryGuardA, true);
// do some stuff that might cause reentry of this function
// this section is both early-exit and exception proof, with regards to restoring
// the guard variable to its original state
}
}
我正在寻找一种优雅的方式在C#中使用处理模式(或者可能是其他一些机制)来做到这一点?我认为将委托传递给调用可能会起作用,但似乎比上面的警卫更容易出错.建议欢迎!
就像是:
void someFunction() {
if(!reentryGuard) {
using(var guard = new BoolGuard(ref reentryGuard, true)) {
// do some stuff that might cause reentry of this function
// this section is both early-exit and exception proof, with regards to restoring
// the guard variable to its original state
}
}
}
理解上述代码不起作用.
解决方法:
你是对的…没有不安全的代码,你不能保存by-ref参数的地址.但是,根据您可以更改整体设计的程度,您可以创建一个“可保护”类型,这样它就是一个包含实际防护值的引用类型.
例如:
class Program
{
class Guardable<T>
{
public T Value { get; private set; }
private sealed class GuardHolder<TGuardable> : IDisposable where TGuardable : Guardable<T>
{
private readonly TGuardable _guardable;
private readonly T _originalValue;
public GuardHolder(TGuardable guardable)
{
_guardable = guardable;
_originalValue = guardable.Value;
}
public void Dispose()
{
_guardable.Value = _originalValue;
}
}
public Guardable(T value)
{
Value = value;
}
public IDisposable Guard(T newValue)
{
GuardHolder<Guardable<T>> guard = new GuardHolder<Guardable<T>>(this);
Value = newValue;
return guard;
}
}
static void Main(string[] args)
{
Guardable<int> guardable = new Guardable<int>(5);
using (var guard = guardable.Guard(10))
{
Console.WriteLine(guardable.Value);
}
Console.WriteLine(guardable.Value);
}
}
内容总结
以上是互联网集市为您收集整理的C#中的Guard对象全部内容,希望文章能够帮你解决C#中的Guard对象所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。