Ami*_*abh 1 .net lambda c#-3.0
我使用以下代码将属性传递给lambda表达式.
namespace FuncTest
{
class Test
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.Name = "My Test";
PrintPropValue(t => t.Name);
}
private static void PrintPropValue(Func<string> func)
{
Console.WriteLine(func.Invoke());
}
}
}
Run Code Online (Sandbox Code Playgroud)
这不编译.我只是希望函数能够获取属性并能够进行评估.
A Func<string>没有任何参数 - 但是你的lambda表达式确实如此.
目前尚不清楚您是否真的需要Func<Test, string>- 在这种情况下,您需要传入Test调用委托时的实例- 或者您是否需要Func<string>捕获特定的Test实例.对于后者:
using System;
class Test
{
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.Name = "My Test";
// Note: parameterless lambda expression
PrintPropValue(() => t.Name);
// Demonstration that the reference to t has been captured,
// not just the name:
Func<string> lambda = () => t.Name;
PrintPropValue(lambda);
t.Name = "Changed";
PrintPropValue(lambda);
}
private static void PrintPropValue(Func<string> func)
{
Console.WriteLine(func.Invoke());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
607 次 |
| 最近记录: |