using System;
namespace _1._75_Using_a_delegate
{
public class Program
{
public delegate int Calculate(int x, int y);
public int Add(int x, int y) { return x + y; }
public int Multiply(int x, int y) { return x * y; }
public void UseDelegate()
{
Calculate calc = Add;
Console.WriteLine(calc(3, 4)); //Displays 7
calc = Multiply;
Console.WriteLine(calc(3, 4));//Displays 12
}
public static void Main()
{
//call and execute UseDelegate()
}
}
}
这应该输出7和12的上述结果。
委托函数不能直接从当前状态的main调用。
答案 0 :(得分:2)
您无法从静态方法调用非静态方法,因此您必须实现另一个类,如
Try
Dim conn As New SqlConnection("Data Source=HAMSE_PC\SQLEXPRESS;Initial Catalog=Body;Integrated Security=True")
cmd.Connection = conn
conn.Open()
Dim UpdateSQL, name, dis, username, pass As String
name = txtname.Text
dis = txtdiscription.Text
username = txtusername.Text
pass = txtpassword.Text
UpdateSQL = "Update Users Set "
UpdateSQL &= "FullName=@fullname,Phone=@phone,Date=@date,Discription=@dis,UserName=@user,Password=@pass "
UpdateSQL &= "Where User_ID=@ID"
cmd.CommandText = UpdateSQL
cmd.Parameters.AddWithValue("@fullname", name)
cmd.Parameters.AddWithValue("@date", Convert.ToDateTime(txtdate.Text).Date)
cmd.Parameters.AddWithValue("@dis", dis)
cmd.Parameters.AddWithValue("@user", username)
cmd.Parameters.AddWithValue("@pass", pass)
cmd.Parameters.AddWithValue("@phone", Convert.ToInt32(txtphone.Text).ToString)
cmd.Parameters.AddWithValue("@ID", Convert.ToInt32(txtid.Text).ToString)
If txtname.Text = "" Or txtdate.Text = "" Or txtusername.Text = "" Or txtpassword.Text = "" Or txtphone.Text = "" Then
MessageBox.Show("to update please fill the empty Columns ", "Attention")
txtname.Focus()
Else
cmd.ExecuteNonQuery()
MsgBox("Updated")
Dim dt As New DataTable
Dim ds As New DataSet
ds.Tables.Add(dt)
Dim da As New SqlDataAdapter
da = New SqlDataAdapter("select * from Users", conn)
da.Fill(dt)
UsersDataGridView.DataSource = dt.DefaultView
txtname.Text = ""
txtdate.Text = ""
txtusername.Text = ""
txtpassword.Text = ""
txtphone.Text = ""
ID()
End If
conn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
您可以通过主要方法调用它,例如
internal class Check
{
public delegate int Calculate(int x, int y);
public int Add(int x, int y)
{
return x + y;
}
public int Multiply(int x, int y)
{
return x * y;
}
public void UseDelegate()
{
Calculate calc = Add;
Console.WriteLine(calc(3, 4)); //Displays 7
calc = Multiply;
Console.WriteLine(calc(3, 4));//Displays 12
}
}
答案 1 :(得分:1)
你根本没有调用这个方法,现在你不能,因为Main
方法是静态的,你的方法不是。
我建议将代码拆分为第二类,这样更容易调用。 (而不是使所有方法都是静态的)
public class Assignment
{ /* all code except the Main method goes here */ }
然后,在Main
方法中,实例化Assignment
类的实例并调用UseDelegate
:
public static void Main()
{
Assignment a = new Assignment();
a.UseDelegate();
Console.ReadKey(); // to prevent the console from closing immediate
}