c# 公共接口和签名变量

问题描述 投票:0回答:1

我正在尝试完全重写我的第一个 C# Windows 窗体应用程序。更好的做事方式。该过程的一部分是我想开始使用接口。我选择了一个只有一个签名变量和一个基于接口的方法的类。接口的签名变量以表单形式赋值,然后调用该类。当类执行时,这个公共变量没有值。我不确定我在这里做错了什么。感谢您提供的任何帮助。 接口定义。

    public interface IAbsolutePath
     {
         string strPath { get; set; }
         bool CheckForDriveSelected();
     }

调用接口

     public partial class frm_Copydata : Form
     {
         public string strPath{get; set;}
         public frm_Copydata()
         {
             InitializeComponent();
         }

         private void btn_SelectInput_Click_1(object sender, EventArgs e)
         {
             // bool bolInputSelected = true;
             if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
             {
                 txb_InputFolderPath.Text = folderBrowserDialog1.SelectedPath;
                 strPath = txb_InputFolderPath.Text;
                 IAbsolutePath WasDriveSelected = new cl_CheckForDriveSelected();
                 bool bolDriveLetter = WasDriveSelected.CheckForDriveSelected();
             }
         }
     }

最后是类和方法。

class cl_CheckForDriveSelected : IAbsolutePath
{
    public string strPath { get; set; }
    public bool CheckForDriveSelected()
    {
        DriveInfo[] drives = DriveInfo.GetDrives();
        

        for (int i = 0; i < drives.Count(); i++)
        {
            var strtest = drives[i].Name;
            if (strPath == drives[i].Name)
            {
                var strMsgBoxTitle = "Select a folder for input";
                var strMsgBoxMsg = "You must choose a folder and not a drive letter." +
                       "\n" +
                        "Please make another selection";
                MessageBoxButtons btnButtons = MessageBoxButtons.OK;
                MessageBox.Show(strMsgBoxMsg, strMsgBoxTitle, btnButtons, MessageBoxIcon.Error);
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    }
}

在将接口应用到可以使用此类逻辑的应用程序的其他区域之前,我希望先尝试一些简单的东西。

c# winforms interface
1个回答
0
投票

您没有为

IAbsolutePath
实现的类的公共属性赋值。您需要通过以下方式赋值:

 IAbsolutePath WasDriveSelected = new cl_CheckForDriveSelected()
  {
        strPath =  txb_InputFolderPath.Text
  }

frm_Copydata 中不需要

strPath
字段。

© www.soinside.com 2019 - 2024. All rights reserved.