其实他们两个都是委托【代理】的简写形式。
private void button5_Click(object sender, EventArgs e)
{
//类似委托功能
Func<string, int> test = TsetMothod;
Console.WriteLine(test("123"));
Func<string, int> test1 = TsetMothod;
//只需要调用这个类就可以减少重复的代码
CallMethod<string>(test1, "123");
//或者采用这种
CallMethod<string>(new Func<string, int>(TsetMothod), "123");
CallMethod(new Func<string, int>(TsetMothod), "123");
}
public static void CallMethod<T>(Func<T, int> func, T item)
{
try
{
int i = func(item);
Console.WriteLine(i);
}
catch (Exception e)
{
}
finally
{
}
}
public static int TsetMothod(string name)
{
if (string.IsNullOrEmpty(name))
{
return 1;
}
return 0;
}
----------------------------------Func例-------------------------------------------
private void button6_Click(object sender, EventArgs e)
{
// Note that each lambda expression has no parameters.
LazyValue<int> lazyOne = new LazyValue<int>(() => ExpensiveOne());
LazyValue<long> lazyTwo = new LazyValue<long>(() => ExpensiveTwo("apple"));
Console.WriteLine("LazyValue objects have been created.");
// Get the values of the LazyValue objects.
Console.WriteLine(lazyOne.Value);
Console.WriteLine(lazyTwo.Value);
}
static int ExpensiveOne()
{
Console.WriteLine("\nExpensiveOne() is executing.");
return 1;
}
static long ExpensiveTwo(string input)
{
Console.WriteLine("\nExpensiveTwo() is executing.");
return (long)input.Length;
}
}
class LazyValue<T> where T : struct
{
private Nullable<T> val;
private Func<T> getValue;
// Constructor.
public LazyValue(Func<T> func)
{
val = null;
getValue = func;
}
public T Value
{
get
{
if (val == null)
// Execute the delegate.
val = getValue();
return (T)val;
}
}
}
本文详细介绍了C#中的Action与Func两种委托类型的区别及应用实例,包括无返回值的Action委托和有返回值的Func委托,并通过代码示例展示了如何使用这两种委托简化代码。
1440

被折叠的 条评论
为什么被折叠?



