C#这个操作符类字段声明 [英] C# this operator in class field declaration

查看:273
本文介绍了C#这个操作符类字段声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个纯粹的学术问题 - 我已经找到了getaround很轻松了。

This is a purely academic question - I have found a getaround easily enough.

在移植VB.Net类C#中,我来到现场,其中使用this关键字作为参数在一个新的()语句类的声明。编译器说,关键字这不是在目前情况下,可用'(VB编译器认为没有问题,这种状况)。我很容易被现场的初始化移动到类的构造器解决此得到。

While porting a VB.Net class to C#, I came upon the declaration of a field in a class which used the this keyword as a parameter in a new() statement. The compiler said the "Keyword 'this' is not available in the current context' (the VB compiler saw no problem with this state of affairs). I easily got around this by moving the field's initialization to the contructor of the class.

编辑:在阅读的意见后,我添加以下代码块

edit: after reading comments, I added the following code block

 
    public class cTransactions
    {
        private List Trans = new List();
        private List Archive = new List();
        private cDDs Debits = new cDDs(this); // complier error 
                                            //Keyword 'this' is not available in the current context
        private string path = Directory.GetCurrentDirectory() + "\";
        private bool dirty = false;
        private int LastID;
        // followed by Property declarations, ctor, methods etc.
        //...
    }
     

不过,我找不到关键字的任何引用'这个'一类的构造函数执行之前不被使用(虽然我可能已经错过了启示,在500+语言规范的页面)。这样的话,或者我应该寻找以前到外地报关行之一的一些错误?

However, I cannot find any reference to the keyword 'this' not being available before the execution of a class' constructor (though I may have missed that revelation in the 500+ pages of the language specification). Is this the case or should I be looking some error in one of the lines prior to the field declaration?

推荐答案

综观 C#语言规范部分7.6.7:

7.6.7此访问

A 此访问的只有在一个实例
构造函数,实例方法或实例访问的块是允许的。 ...(具体略)......在比上面列出的
以外的上下文中的基本表达式的这种
中使用的是编译时错误。尤其是,它不是
可以参考这在静态方法,静态属性
访问,或在一个域声明的变量初始化。

A this-access is permitted only in the block of an instance constructor, an instance method, or an instance accessor. ... (specifics omitted) ... Use of this in a primary-expression in a context other than the ones listed above is a compile-time error. In particular, it is not possible to refer to this in a static method, a static property accessor, or in a variable-initializer of a field declaration.

因此,在上面的例子中的可变初始化使用它是一个编译时间错误。要修复它,将初始化到构造。

Therefore, using it in a variable-initializer in the example above is a compile-time error. To fix it, move the initialization into the constructor.

这篇关于C#这个操作符类字段声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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