静态引用另一个.cs文件

时间:2017-07-21 17:08:00

标签: c#

我忽略了一些简单的想法。我有一个带复选框的表单。我需要知道是否在不同的cs文件/类中选中了复选框,以了解是否要创建列标题Option1或Option2。
Form1(公共部分类)代码:

public bool Checked
{
    get 
    { 
        return checkBox1.Checked; 
    }   
}

在我的Export1类中,我有一个私有的void CreateCell1,它接收要导出的数据(从数据表创建一个excel文件)。我无法工作的代码部分是:

if (Form1.Checked.Equals("true"))
{
    newRow["Option1"] = date2;
}
else
{
    newRow["Option2"] = date2;
}

我得到-Error 1非静态字段,方法或属性'Matrix1.Form1.Checked.get'

需要对象引用

我忽略了什么?

2 个答案:

答案 0 :(得分:4)

嗯,这里的问题正是编译器告诉你的。您需要对象引用才能访问该属性。

请允许我解释一下。

在C#中,默认情况下,类成员(字段,方法,属性等)是实例成员。这意味着它们与它们所属的类的实例相关联。这样可以实现以下行为:

public class Dog
{
    public int Age { get; set; }
}

public class Program
{
    public static void Main()
    {
        var dog1 = new Dog { Age: 3 };
        var dog2 = new Dog { Age: 5 };
    }
}

Dog的两个实例都具有属性Age,但是该值与Dog的实例相关联,这意味着每个实例都可能不同。

在C#中,与许多其他语言一样,有一些名为static类的成员。当一个类成员被声明为static时,该成员不再被绑定到它所属的类的实例。这意味着我可以执行以下操作:

public class Foo
{
    public static string bar = "bar";
}

public class Program
{
    public static void Main()
    {
        Console.WriteLine(Foo.bar);
    }
}

bar类的Foo字段被声明为static。这意味着Foo的所有实例都是相同的。事实上,我们甚至不必初始化Foo的新实例来访问它。

您在这里面临的问题是,虽然Form1不是静态类,而Checked不是静态属性,但您将其视为静态属性。为了使您尝试执行的操作,您需要创建Form1实例并访问该实例的Checked属性。

根据程序的结构,有很多方法可以做到这一点。如果在您尝试访问Form1的范围内创建了Checked,那么这将很简单。如果Form1产生新范围,那么通常的做法是在构造函数中传递对它的引用。

例如,如果Form1创建了新的Form2,那么我们会执行以下操作:

public class Form2 : Form
{
    private Form1 parent;
    public Form2(Form1 parent)
    {
        this.parent = parent;
        InitializeComponent();
    }
}

然后,您可以在parent中访问Form2。当然,根据程序的结构,具体实现方式会有所不同。但是,一般模式是相同的。将对Form1的引用从它创建的范围传递给新类,然后从那里访问它。

答案 1 :(得分:0)

您需要以某种方式访问​​您要检查的Form1的特定实例。

有几种方法可以做到:

  1. 将实例传递给类构造函数
  2. 将另一个类的公共属性设置为表单实例
  3. 直接将实例传递给方法
  4. 例如:

    public class SomeOtherClass
    {
        // One option is to have a public property that can be set
        public Form1 FormInstance { get; set; }
    
        // Another option is to have it set in a constructor
        public SomeOtherClass(Form1 form1)
        {
            this.FormInstance = form1;
        }
    
        // A third option would be to pass it directly to the method
        public void AMethodThatChecksForm1(Form1 form1)
        {
            if (form1 != null && form1.Checked)
            {
                // Do something if the checkbox is checked
            }
        }
    
        // This method uses the local instance of the Form1 
        // that was either set directly or from the constructor
        public void AMethodThatChecksForm1()
        {
            AMethodThatChecksForm1(this.FormInstance);
        }
    }
    

    此类需要使用以下方法之一由实例form1实例化:

    // Pass the instance through the constructor
    var someOtherClass = new SomeOtherClass(this);
    
    // Or set the value of a property to this instance
    someOtherClass.FormInstance = this;
    
    // Or pass this instance to a method of the class
    someOtherClass.AMethodThatChecksForm1(this);