Rob*_*anc 17 c# visual-studio-2010
以下代码用于在vs2008下正常工作:
namespace N2.Engine.Globalization
{
public class DictionaryScope : Scope
{
object previousValue;
public DictionaryScope(IDictionary dictionary, object key, object value)
: base(delegate
{
if (dictionary.Contains(key))
previousValue = dictionary[key];
dictionary[key] = value;
}, delegate
{
if (previousValue == null)
dictionary.Remove(key);
else
dictionary[key] = previousValue;
})
{
}
}
}
Run Code Online (Sandbox Code Playgroud)
但现在报告非静态字段,方法或属性'N2.Engine.Globalization.DictionaryScope.previousValue'需要对象引用
编译器似乎发生了变化?任何解决方法?
更新:
关于使用虚拟方法的建议.这可能也不会起作用,因为从基础构造函数调用虚方法,我认为这也是不可能的?
这是Scope(基类)的实现:
public class Scope: IDisposable
{
Action end;
public Scope(Action begin, Action end)
{
begin();
this.end = end;
}
public void End()
{
end();
}
#region IDisposable Members
void IDisposable.Dispose()
{
End();
}
#endregion
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 18
更新:
§7.5.7此访问权限
一个this访问由保留字的
this.此访问:
Run Code Online (Sandbox Code Playgroud)this甲此访问仅在允许块实例构造,实例方法,或实例访问的.
这些都不是.4.0编译器看起来是正确的.据推测它并不快乐,因为这实际上提供了this在未初始化类型时的访问.也许;-p
请注意,我期望它是不是真的this.someField导致此-更多的是使用一个字段会导致this被捕获,这意味着它要在葫芦this实例到编译器生成的类-就好像你这样写:
public MyCtor() : base( new SomeType(this).SomeMethod ) {...}
Run Code Online (Sandbox Code Playgroud)
C#3.0编译器发现了上面的滥用行为this.
转载.调查.它看起来像是一个解决this构造函数链中隐含的问题.
最可能的解决方法是使用virtual方法而不是委托,并在派生类中简单地覆盖它.
一种解决方法是将实例作为参数传递,因此委托变为"obj => obj.whatever ...",并使用theDelegate(this);.
更简单的repro:
public class MyBase {
public MyBase(Action a) { }
}
public class MySub : MyBase {
private string foo;
// with "this.", says invalid use of "this"
// without "this.", says instance required
public MySub() : base(delegate { this.foo = "abc"; }) { }
}
Run Code Online (Sandbox Code Playgroud)
我需要检查的规范,但我不知道是否this 是有效的在这种情况下......所以,4.0编译器可能是正确的.