在public static中从string转换为int

时间:2014-05-14 13:37:47

标签: c#

private class global
{
    public static string str = label4.Text;
    int a = Convert.ToInt32(str);
}

private void button8_Click(object sender, EventArgs e)
{
    string myString = label4.Text;
    int Val = Int32.Parse(myString);
    dataGridView1.Rows.Add(label2.Text, Val * global.a );
}

大家好我在这里有一些问题,然后我将字符串转换为int in private void它工作正常,但后来我尝试将它转换为公共全局它显示错误,任何想法如何修复它?

  

DB2.Form2.global.a'由于其保护级别而无法访问

     

非静态字段,方法或属性需要对象引用" DB2.Form2.global.a

     

非静态字段,方法或属性需要对象引用" DB2.Form2.label4

6 个答案:

答案 0 :(得分:2)

在课程a之外无法看到

global,您应将其公开:

public int a  = Convert.ToInt32(str);

由于global类未标记为static,您可以将其设为静态或创建global的实例。

private static class global
{
    public static int a = ...
}

或不使其静止(但a必须公开):

var myGlobal = new global();
int x = myGlobal.a;

此外:

  • 类应该大写

    public class Global { ... }
    
  • 同样适用于公共属性/字段:

    public int A = 1;
    public string Str = "";
    

答案 1 :(得分:0)

a未定义为全局静态变量。

将其重新定义为public static int a;

答案 2 :(得分:0)

除非该字段是静态的并且字段可以访问,否则您无法在不首先实例化对象的情况下从类访问字段。

答案 3 :(得分:0)

你的int是全局类的私有int。

将其更改为公开和静态。

答案 4 :(得分:0)

a不是静态和公开的。因此要么将其设为公共静态,要么实例化该类并使用该实例来访问。

私人领域无法在课堂外访问。

答案 5 :(得分:0)

变量a是私有的,因此无法在类外部访问,而且它被声明为实例成员而不是静态成员。

您需要根据发布的代码使用情况将其声明为public static int a

您的班级定义应该类似于

private class global
{
    public static string str = label4.Text;
    public static int a;
    a = Convert.ToInt32(str);
}

第一个错误is inaccessible due to its protection level导致因为您将a声明为私有。

导致第二个错误An object reference is required for the non-static field, method, or property,因为您尝试以静态成员身份访问实例成员。