房地产是无法访问由于其保护级别 [英] Property is inaccessible due to its protection level

查看:121
本文介绍了房地产是无法访问由于其保护级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要张贴到多行文本框。的数据是从一个不同的方法,即将在一个单独的类

 类转换器
{
    公共静态无效的转换(对象源,FileSystemEventArgs F)
    {
        // ...一些工作,现在做发布此数据的WinForms
        Form1.textBox1 =文件复制++
                         DateTime.Now.ToString(HH:MM:SS TT)+
                         Environment.NewLine;
    }
}
 

我不能够从这个类访问 textBox1的。它说:

  

Form1.textBox1'不可访问由于其保护级别
  对象引用是所必需的非静态字段,方法或属性Form1.textBox1'

解决方案

您可以将文本框更改为公共​​,通过Form1的实例,但这些方法违反了封装的基本租户,该类转换不应该知道Form1的任何东西,它的控制。

一个更好的方法是类转换器定义将由类调用如果调用者希望得到通知,并更新转换器类后,一些内部(至文本框)已完成其工作的事件。

 类转换器
{
   公共委托无效OnCopyComplete(字符串的文件);
   公共事件OnCopyComplete CopyComplete;
   公共静态无效的转换(对象源,FileSystemEventArgs F)
   {
       // ...有些工作做好,现在通知主叫
       如果(CopyComplete!= NULL)CopyComplete(source.ToString());
   }
}
 

而在Form1中实例

  //告诉给这个类要在工作结束后要通知的转换器类
converter.CopyComplete + =新converter.OnCopyComplete(UpdateMyLabels);
converter.convert(....);


公共无效UpdateMyLabels(字符串的文件)
{
    TextBox1.Text =文件复制++ DateTime.Now.ToString(HH:MM:SS TT)+ Environment.NewLine;
}
 

I need to post to the multiline TextBox. The data is coming from a different method in a separate class.

class converter
{
    public static void convert(object source, FileSystemEventArgs f)
    {
        //... some job done now post this data to winforms
        Form1.textBox1 = "File Copied" + "  " + 
                         DateTime.Now.ToString("HH:mm:ss tt") +
                         Environment.NewLine;
    }
}

I'm not able to access textBox1 from this class. It says:

Form1.textBox1' is inaccessible due to its protection level
An object reference is required for the non-static field, method, or property Form1.textBox1'

解决方案

You can change the TextBox to public, pass an instance of Form1 but these approaches violates the basic tenants of encapsulation, the class converter should not know anything of Form1 and its controls.

A better approach is for the class converter to define an event that will be called by the class if a caller desires to be notified and update something internal (the textBox) after the converter class has done its job.

class converter
{
   public delegate void OnCopyComplete(string file);
   public event OnCopyComplete CopyComplete;
   public static void convert(object source, FileSystemEventArgs f)
   {
       //... some job done now NOTIFY the caller 
       if(CopyComplete != null) CopyComplete(source.ToString());
   }
}

And in Form1 instance

// tell to the converter class that this class wants to be notified when the work is finished
converter.CopyComplete += new converter.OnCopyComplete(UpdateMyLabels);
converter.convert(....);


public void UpdateMyLabels(string file)
{
    TextBox1.Text = "File Copied" + "  " + DateTime.Now.ToString("HH:mm:ss tt") + Environment.NewLine;
}

这篇关于房地产是无法访问由于其保护级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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