本人刚学习C#,现在遇到这样一个问题:
要求自己定义一个类,比如叫Timer,要实现这样一个功能:
当在
static void Main()
{
Timer time = new Timer(Console.WriteLine("a"));
}
运行时,可以在控制台把这个函数执行5遍
a
a
a
a
a,
而如果new Timer()这个括号的参数变了的话,也能执行括号中的函数
比如:
Timer time = new Timer(Class1.aaa());
其中Class1.aaa()是我自己定义的完成某个功能的函数,也是执行5遍。
谢谢大家,请帮帮我吧。
要求自己定义一个类,比如叫Timer,要实现这样一个功能:
当在
static void Main()
{
Timer time = new Timer(Console.WriteLine("a"));
}
运行时,可以在控制台把这个函数执行5遍
a
a
a
a
a,
而如果new Timer()这个括号的参数变了的话,也能执行括号中的函数
比如:
Timer time = new Timer(Class1.aaa());
其中Class1.aaa()是我自己定义的完成某个功能的函数,也是执行5遍。
谢谢大家,请帮帮我吧。
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication6
{
class Program
{ class Timer
{
public Timer(Delegate d, object[] args)
{
for (int i = 0; i < 5; i++)
{
d.Method.Invoke(this, args);
}
}
}
public delegate void dWriteInfo(string str); public static void WriteInfo(string str)
{
Console.WriteLine(str);
}
static void Main(string[] args)
{
new Timer(new dWriteInfo(WriteInfo), new object[] { "aa" });
new Timer(new Class1.daaa(Class1.aaa), new object[] { "aa" ,"bbb"}); Console.Read();
}
}
public class Class1
{
public delegate void daaa(string str1, string str2);
public static void aaa(string str1, string str2)
{
Console.WriteLine("{0}:{1}", str1, str2);
}
}
}
{
Action _a;
public Timer(Action a)
{
_a = a;
}
public void Run()
{
for(int i=0; i<5; ++i)
a();
}
}
public static void Main()
{
Timer t = new Timer(delegate() { Console.WriteLine("a"); })
t.Run();
}
class Timer
{
Action _a;
Action<T> _a1;
T _t;
public Timer(Action a)
{
_a = a;
}
public Timer(Action<T> a, T t)
{
_a = a; _t = t;
}
public void Run()
{
for(int i=0; i <5; ++i)
{
if(_a != null)
_a();
if(_a1 != null)
_a1(_t);
}
}
}
{
public void Run(Action a)
{
for (int i = 0; i < 5; ++i)
{
a();
}
}
public void Run<T>(Action<T> a, T t)
{
for (int i = 0; i < 5; ++i)
{
a(t);
}
}
}
class Program8
{
public static void Main()
{
Timer t = new Timer();
t.Run(delegate(string s) { Console.WriteLine(s); }, "Hello world");
}
}
class Timer
{
public void Run(Action a)
{
for (int i = 0; i < 5; ++i)
{
a();
}
}
public void Run<T>(T t, Action<T> a)
{
for (int i = 0; i < 5; ++i)
{
a(t);
}
}
}
class Program8
{
public static void Main()
{
Timer t = new Timer();
t.Run("Hello world", delegate(string s) { Console.WriteLine(s); });
t.Run("Lucifer", Test);
}
public static void Test(string a)
{
Console.WriteLine(a);
}
}
class Timer
{
//因为你的类需要一个函数做为参数,也就是传递函数指针,所以要用一个委托来封装这个函数
//委托的签名要和你要传递的函数签名一样。这里和void aaa()一样。要其他类型的就需要定义对应签名的委托
public delegate void method();
//需要一个method委托对象
public Timer(method d)
{
for(int i=0;i<5;i++)
d(); //执行委托,也就是执行他绑定的方法
}
}class Class1
{
public static void aaa()
{
Console.WriteLine("xxxxxxx");
}
}class ex
{
public static void Main()
{
//实例化委托,和要传递的方法绑定
Timer.method md = new Timer.method(Class1.aaa);
//传递委托,实际就是传递的aaa方法
Timer time = new Timer(md);
Console.Read();
}
}