以下代码在 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;
})
{
}
}
}
但现在它报告非静态字段、方法或属性“N2.Engine.Globalization.DictionaryScope.previousValue”需要对象引用
编译器似乎发生了一些变化?任何解决方法?
更新:
关于使用虚拟方法的建议。这可能也行得通,因为虚方法将从基本构造函数中调用,我认为这也是不可能的?
这里是作用域(基类)的实现:
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
最佳答案
更新:
§ 7.5.7 This access
A this-access consists of the reserved word
this
.this-access:
this
A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor.
这些都不是。 4.0 编译器看起来是正确的。大概它不高兴是因为 this in essential 在类型未初始化时提供了对 this
的访问。也许;-p
请注意,我预计这并不是真正的 this.someField
导致的 - 更多的是字段的 use 导致 this
被捕获,这意味着它想将 this
实例提升到编译器生成的类上——就好像您已经编写了:
public MyCtor() : base( new SomeType(this).SomeMethod ) {...}
C# 3.0 编译器发现了上述对 this
的滥用。
转载。调查。它看起来像是解决构造函数链中隐式 this
的问题。
最可能的解决方法是使用 virtual
方法而不是委托(delegate),并在派生类中简单地覆盖它。
一种解决方法是将实例作为参数传入,因此委托(delegate)变为“obj => obj.whatever...”,并使用 theDelegate(this);
。
更简单的重现:
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"; }) { }
}
我需要检查规范,但我不确定this
在这种情况下是否有效...因此 4.0 编译器可能是正确的。
关于c# - vs2010 beta 2 下的 CS0120 错误 - 需要对象引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1600001/