无法调用类的方法
本文关键字:方法 调用 | 更新日期: 2023-09-27 18:27:00
命名空间与这两个类相同。我需要调用WhatsAppSend类中的xyz()方法。
这是我在Form1.cs 中的方法
public void SendWhatsAppMsg()
{
try
{
WhatsAppSend ws;
ws = new WhatsAppSend(this); //Error Coming on this
ws.xyz(txtNickName.Text.ToString(),
gridSender.Rows[iCurrentChannelNo].Cells[0].Value.ToString(),
gridSender.Rows[iCurrentChannelNo].Cells[1].Value.ToString(),
CreateArrayFrom(i + 1, (i + 1) + iMsgLimitPerNo),
dropWhatsappType.SelectedItem.ToString(),
SendingData(dropWhatsappType.SelectedItem.ToString()),
ext);
}
catch(Exception e)
{
txt.log += e.ToString();
}
}
我试图在另一个类WhatsAppSend.cs 中调用的方法
namespace WhatsApp_Bulk
{
public class WhatsAppSend
{
public static WhatsAppBulk form1;
public WhatsAppSend(WhatsAppBulk _form1)
{
form1 = _form1;
}
public static String line = "";
public static String command = "";
public static string[] dst;
public static int count_sleep = Convert.ToInt32(form1.txtMsgGap.Text);
public static string WhatsAppType = "";
public static string DataToSend = "";
public static string ext = "";
public void xyz(string nickname, string sender, string password, string[] Datadst, string DataWhatsAppType, string DataDataToSend, string Dataext)
{
dst = Datadst;
WhatsAppType = DataWhatsAppType;
DataToSend = DataDataToSend;
ext = Dataext;
WhatsApp wa = new WhatsApp(sender, password, nickname, true);
}
}
}
错误:
System.TypeInitializationException: The type initializer for 'WhatsApp_Bulk.WhatsAppSend' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at WhatsApp_Bulk.WhatsAppSend..cctor() in d:'WhatsApp Bulk'WhatsApp Bulk'WhatsAppSend.cs:line 32
--- End of inner exception stack trace ---
at WhatsApp_Bulk.WhatsAppSend..ctor(WhatsAppBulk _form1)
at WhatsApp_Bulk.WhatsAppBulk.SendWhatsAppMsg() in d:'WhatsApp Bulk'WhatsApp Bulk'Form1.cs:line 367
请告诉我哪里出了问题
public static int count_sleep = Convert.ToInt32(form1.txtMsgGap.Text);
当form1
为null
时,此行在类型初始化时执行。您可以在稍后执行的实例构造函数中设置form1
。
这是TypeInitializationException
的常见原因。
UPD:
我可以建议以下
public class WhatsAppSend
{
public WhatsAppBulk form1;
public WhatsAppSend(WhatsAppBulk _form1)
{
form1 = _form1;
count_sleep = Convert.ToInt32(form1.txtMsgGap.Text);
}
public String line = "";
public String command = "";
public string[] dst;
public int count_sleep;
public string WhatsAppType = "";
public string DataToSend = "";
public string ext = "";
public void xyz(string nickname, string sender, string password, string[] Datadst, string DataWhatsAppType, string DataDataToSend, string Dataext)
{
dst = Datadst;
WhatsAppType = DataWhatsAppType;
DataToSend = DataDataToSend;
ext = Dataext;
WhatsApp wa = new WhatsApp(sender, password, nickname, true);
}
}
请注意,公共实例字段仍然是糟糕的设计,但我不知道你会在哪个上下文中使用这个类,所以我将它们保留为公共的。
将WhatsAppSend类设为静态类,然后调用,根据我的假设,该类中声明的变量是静态变量,因此该类应该具有相同的访问修饰符。