强类型属性访问的扩展方法
我有以下类层次结构,
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);
}
}
但现在编译器说
无法从用法中推断出方法“ConsoleApplication1.TestExtensions.Property(ConsoleApplication1.Test, System.Linq.Expressions.Expression>)”的类型参数。尝试显式指定类型参数。
我想要类似 mvc Html.TextBoxFor(x => x.Name) 方法。 是否可以编写要使用的扩展,如 Main
方法中所示?
I have the following class hierarchy
class Test
{
public string Name { get; set; }
}
class TestChild : Test
{
public string Surname { get; set; }
}
I can't change the Test class. I want to write following extension method like this:
static class TestExtensions
{
public static string Property<TModel, TProperty>(this Test test, Expression<Func<TModel, TProperty>> property)
{
return property.ToString();
}
}
To be able to use it in the following way:
class Program
{
static void Main(string[] args)
{
TestChild t = new TestChild();
string s = t.Property(x => x.Name);
}
}
But now compiler says
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.
I want to have something like mvc Html.TextBoxFor(x => x.Name) method.
Is it possible to write extension to be used as shown in the Main
method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要指定调用的通用参数,仅此而已:
编辑:
我的错。我错过了真正的问题:
这应该使您可以省略通用参数。我假设您也在这个方法中处理真实代码来获取属性名称?如果没有,您可能实际上想要这个:
You need to specify the generic arguments for the call, that's all:
EDIT:
My fault. I missed the real problem:
This should make it so you can omit the generic arguments. I assume you are also processing real code in this method to get the property name? If not, you may actually want this:
编译器应该能够推断出第一个参数......
The compiler should be able to infer the first argument...