如何在类中传递没有静态表单的表单引用

  • 本文关键字:表单 静态 引用 c# .net
  • 更新时间 :
  • 英文 :


我的标题可能没有任何意义。由于我不知道如何表达,我将通过举一个例子把我的问题翻译成英语。(英语是我的第三语言)

所以基本上,我想在我的类中做到这一点:

public void beheerToegang(ref Form frm)
{    
}

代替这个(静态引用我的表单的实际名称):

public void beheerToegang(ref frmInkomsteBlad frm)
{    
}

好的,我看到了你遇到的问题的图片。

首先,您不需要在方法中添加ref(并考虑更好的命名)。已被引用对象

public void beheerToegang(Form frm)
{    
}
接下来,您可以从自定义表单示例(未测试代码)中原样使用该方法:
frmInkomsteBlad form1 = new frmInkomsteBlad();
beheerToegang(form1);

然后像这样访问它:

public void beheerToegang(Form frm)
{    
  string formTitle = frm.Text;
}

但是你不能访问自定义表单中定义的属性/字段。例子:

public class frmInkomsteBlad : Form{
  public string CustomString{get;set;} // this property cannot be accessed
}
然而,有一些方法可以解决这个问题,首先是使用类型转换:
public void beheerToegang(Form frm)
{   
  if(frm is frmInkomsteBlad){
    frmInkomsteBlad typeCastedForm = (frmInkomsteBlad)frm;
    string customString = typeCastedForm.CustomString;
  }
}

上面的例子是不好的做法,但很容易实现。如果您更关心更好的实践,可以考虑使用接口。例子:

public interface ICustomForm{
  string Title{get;set;}
  string CustomString{get;set;}
  object CustomObject{get;set;}
}

在你的frmInkomsteBlad表单中实现它。

public class frmInkomsteBlad : Form, ICustomForm{
  public string Title{
    get{
     return this.Text;
    }
    set{
     this.Text = value;
    }
  }
  //other implementation here
}

那么你可以这样使用:

public void beheerToegang(ICustomForm frm)
{   
  string customString = frm.CustomString;
  string title = frm.Title;
  object customObject = frm.CustomObject;
}

你能再解释一下你的问题吗?为什么要使用ref这个关键字?表单是一个对象,所以如果你想操作它,你可以使用

public void beheerToegang(Form frm)

是问题在'如何调用'方法在toegang或它是别的东西。我不清楚?看来你是荷兰人,如果你想的话可以用荷兰语问这个问题。这是我的母语。

如果问题仅仅是调用方法,那么您可以使用:

beheerToegang(ref yourformname);

相关内容

最新更新