字段初始值设定项不能引用非静态字段,方法或属性'test.Form1.txtRem [英] A field initializer cannot reference the non-static field, method, or property 'test.Form1.txtRem

查看:95
本文介绍了字段初始值设定项不能引用非静态字段,方法或属性'test.Form1.txtRem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个Windows窗体应用。



调试时有两个错误



错误1字段初始值设定项不能引用非静态字段,方法或属性'test.Form1.SplitInLine(string)'





错误2字段初始化程序无法引用非静态字段,方法或属性'test.Form1.txtRem



这里是代码



i am making a windows form app.

there are two error while debug

Error 1 A field initializer cannot reference the non-static field, method, or property 'test.Form1.SplitInLine(string)'


Error 2 A field initializer cannot reference the non-static field, method, or property 'test.Form1.txtRem

here is the code

string SplitInLine(string forSplit)
        {
            string[] strSplit = forSplit.Split(new char[] { '#' });
            string forReturn = "";
            for (int i = 0; i < strSplit.Length; i++)
                forReturn += (i + 1).ToString() + "." + strSplit[i] + "\n";
                return forReturn;
        }
        string remotersInLine = SplitInLine(txtRem.Text);

推荐答案

来自C#规范:

From C# specification:
Quote:

实例字段的变量初始值设定项无法引用正在创建的实例。

A variable initializer for an instance field cannot reference the instance being created.

这意味着您无法使用其他实例成员初始化一个实例成员*,因为它当时不可用...



*属性或方法

It means you can't initialize one instance member* using an other instance member, as it does not available at that time...

*property or method


消息很明确:你不能这样做。此功能通常会阻止您使用可能尚未准备好的字段初始化字段。在您的情况下, SplitInLine 是实例方法。这意味着它可以通过(隐式)方法参数this访问实例。通过this引用,您可以访问所有其他即时成员。但是,您如何知道您在此方法中使用的其他实例是否已初始化?这并不总是可行的。当两个字段试图互相使用时对图像进行成像。



所以,你应该这样做:
The message is quite clear: you just cannot do it. This feature generally prevents you from initialization of the field with something which might not be yet ready. In your case, SplitInLine is the instance method. It means that it has access to the instance through the (implicit) method parameter "this". Through "this" reference, you can access all other instant members. But how would you know if some other instance you use in this method is already initialized? This is not always possible. Imaging the case when two fields tried to use each other.

So, instead, you should do something like this:
class MyClass {

    internal MyClass() {
        //...
        remotersInLine = SplitInLine(txtRem.Text);
    }

    string SplitInLine(string forSplit) {/* ... */}

    string remotersInLine; // should not be initialized before constructon

    //...

}





你现在能看到这一点吗?



-SA


这篇关于字段初始值设定项不能引用非静态字段,方法或属性'test.Form1.txtRem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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