如何规避匿名方法块使用out参数? [英] How to circumvent using an out parameter in an anonymous method block?

查看:534
本文介绍了如何规避匿名方法块使用out参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的方法不能编译。 Visual Studio中警告说,out参数可能不是一个匿名方法中使用。在 WithReaderLock(PROC动作)方法需要一个委托无效PROC()

 公共布尔TryGetValue(TKEY的关键,走出TValue值)
{
布尔得到= FALSE;
WithReaderLock(代表
{
获得= dictionary.TryGetValue(键,超时值);
});
得到了回报;
}



什么是获得这种行为的最好方法? (请从提供的线程字典建议不要,这个问题是为了解决一般输出参数问题)。


解决方案

 公共BOOL TryGetValue(TKEY的关键,走出TValue值)
{
布尔得到= FALSE;
TValue TMP =默认(TValue); //为明确赋值
WithReaderLock(代表
{
获得= dictionary.TryGetValue(键,出TMP);
});
值= tmp目录;
得到了回报;
}



(编辑 - 小bug)



有关信息,在.NET 3.5,你可能想使用的,而不是滚动您自己的动作委托,因为人们会更多的承认它。即使是在2.0,有很多无效美孚()代表:的ThreadStart MethodInvoker ,等等 - 但动作是最容易遵循;-p


The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().

public Boolean TryGetValue(TKey key, out TValue value)
{
    Boolean got = false;
    WithReaderLock(delegate
    {
        got = dictionary.TryGetValue(key, out value);
    });
    return got;
}

What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).

解决方案

public bool TryGetValue(TKey key, out TValue value)
{
    bool got = false;            
    TValue tmp = default(TValue); // for definite assignment
    WithReaderLock(delegate
    {
        got = dictionary.TryGetValue(key, out tmp);
    });
    value = tmp;
    return got;
}

(edited - small bug)

For info, in .NET 3.5 you might want to use the Action delegate instead of rolling your own, since people will recognise it more. Even in 2.0, there are lots of void Foo() delegates: ThreadStart, MethodInvoker, etc - but Action is the easiest to follow ;-p

这篇关于如何规避匿名方法块使用out参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆