【发布时间】:2010-12-13 18:22:04
【问题描述】:
我有以下类层次结构
class Test
{
public string Name { get; set; }
}
class TestChild : Test
{
public string Surname { get; set; }
}
我无法更改 Test 类。我想像这样编写以下扩展方法:
static class TestExtensions
{
public static string Property<TModel, TProperty>(this Test test, Expression<Func<TModel, TProperty>> property)
{
return property.ToString();
}
}
为了能够通过以下方式使用它:
class Program
{
static void Main(string[] args)
{
TestChild t = new TestChild();
string s = t.Property(x => x.Name);
}
}
但是现在编译器说
无法从用法中推断方法“ConsoleApplication1.TestExtensions.Property(ConsoleApplication1.Test, System.Linq.Expressions.Expression>)”的类型参数。尝试明确指定类型参数。
我想要类似 mvc Html.TextBoxFor(x => x.Name) 方法。
是否可以编写扩展名,如Main 方法所示使用?
【问题讨论】:
标签: c# lambda extension-methods expression strong-typing