Sly*_*Sly 2 c# lambda extension-methods expression strong-typing
我有以下类层次结构
class Test
{
public string Name { get; set; }
}
class TestChild : Test
{
public string Surname { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我无法改变Test类.我想写下面这样的扩展方法:
static class TestExtensions
{
public static string Property<TModel, TProperty>(this Test test, Expression<Func<TModel, TProperty>> property)
{
return property.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
能够以下列方式使用它:
class Program
{
static void Main(string[] args)
{
TestChild t = new TestChild();
string s = t.Property(x => x.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
但现在编译说
无法从用法中推断出方法"ConsoleApplication1.TestExtensions.Property(ConsoleApplication1.Test,System.Linq.Expressions.Expression>)"的类型参数.尝试显式指定类型参数.
我希望有类似mvc Html.TextBoxFor(x => x.Name)方法的东西.是否可以编写扩展以便如Main方法中所示使用?
您需要为调用指定通用参数,即全部:
string s = t.Property<TestChild, string>(x => x.Name);
Run Code Online (Sandbox Code Playgroud)
编辑:
我的错.我错过了真正的问题:
public static string Property<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> property)
{
return property.ToString();
}
Run Code Online (Sandbox Code Playgroud)
这应该使它可以省略泛型参数.我假设您还在处理此方法中的实际代码以获取属性名称?如果没有,你可能真的想要这个:
public static string Property<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> property)
{
var memberExpression = property.Body as MemberExpression;
return memberExpression.Member.Name;
}
Run Code Online (Sandbox Code Playgroud)