c# - 强类型属性访问的扩展方法

标签 c# lambda extension-methods expression strong-typing

我有以下类层次结构

class Test
{
    public string Name { get; set; }
}

class TestChild : Test
{
    public string Surname { get; set; }
}

不能更改测试类。我想像这样编写以下扩展方法:

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);
    }
}

但是现在编译器说

The type arguments for method 'ConsoleApplication1.TestExtensions.Property(ConsoleApplication1.Test, System.Linq.Expressions.Expression>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

我想要类似 mvc Html.TextBoxFor(x => x.Name) 的方法。 是否可以编写要使用的扩展,如 Main 方法所示?

最佳答案

您需要为调用指定通用参数,仅此而已:

string s = t.Property<TestChild, string>(x => x.Name);

编辑:

我的错。我错过了真正的问题:

public static string Property<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> property)
{
    return property.ToString();
}

这应该可以省略通用参数。我假设您也在处理此方法中的真实代码以获取属性名称?如果没有,您可能真的想要这个:

public static string Property<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> property)
{
    var memberExpression = property.Body as MemberExpression;
    return memberExpression.Member.Name;
}

关于c# - 强类型属性访问的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4432120/

相关文章:

c# - LINQ Lambda 连接与计数

linq-to-sql - 具有超过 16 个参数的 Lambda 表达式 Func

C# - 返回枚举?来自静态扩展方法

c# - C# 和 Javascript 中的动态对象属性

c# - 查看模型双向通信

c# - LINQ查询语法(计数操作)

c# - Func<sometype> + Func<sometype> 的真实例子

c# - C# 扩展方法中 "this"参数的默认值

c# - ObservableCollection.AddRange 的最佳性能

c# - Silverlight 5 和 VertexBuffer.GetData()