[英]C# Generic method that can infer its type argument from expression parameter
I am attempting to create a method, that can accept a type of an object as a type parameter, and a reference to one of the object's properties, along with its type.我正在尝试创建一个方法,该方法可以接受对象类型作为类型参数,以及对对象属性之一的引用及其类型。 Something like so:
像这样:
service.DoWork<DateTime>(dt => dt.Ticks)
. service.DoWork<DateTime>(dt => dt.Ticks)
。
I looked at how other libraries were doing such things, and ended up with the following definition:我查看了其他库是如何做这些事情的,最终得到了以下定义:
interface IService
{
void DoWork<TObject, TProperty>(Expression<Func<TObject, TProperty>> propertySelector);
}
Ideally, a user can pass in a type of an object, and then "select" each of its properties with an expression.理想情况下,用户可以传入一种类型的对象,然后使用表达式“选择”其每个属性。 My method can then know the expression selected , along with its type and the type of the object .
我的方法然后可以知道所选的表达式,以及它的类型和对象的类型。
service.DoWork<DateTime>(dt => dt.Ticks);
service.DoWork<DateTime>(dt => dt.TimeOfDay);
service.DoWork<DateTime>(dt => dt.Second);
However, calling the method this way results in the following error:但是,以这种方式调用该方法会导致以下错误:
Using the generic method 'IService.DoWork<TObject, TProperty>(Expression<Func<TObject, TProperty>>)' requires 2 type arguments
If I specfiy the type of the property, then everything works fine:如果我指定属性的类型,那么一切正常:
service.DoWork<DateTime, long>(dt => dt.Ticks);
service.DoWork<DateTime, TimeSpan>(dt => dt.TimeOfDay);
service.DoWork<DateTime, int>(dt => dt.Second);
BUT , this seems really redundant.但是,这似乎是多余的。 The compiler can extract the type from the expression argument that I have provided, and as far as I know a lot of other libraries use such type inferring to provide clean interfaces (Linq, MOQ, FluentAssertions to name a few)
编译器可以从我提供的表达式参数中提取类型,据我所知,很多其他库使用这种类型推断来提供干净的接口(Linq、MOQ、FluentAssertions 等等)
I imagine i need to somehow change my method definition, but I can't seem to find a correct way to do it.我想我需要以某种方式更改我的方法定义,但我似乎无法找到正确的方法来做到这一点。
PS: Here is the complete code snippet. PS:这是完整的代码片段。
using System;
using System.Linq.Expressions;
namespace GenericTypeInterface
{
class Program
{
static void Main(string[] args)
{
IService service = null;
service.DoWork<DateTime>(dt => dt.Ticks);
service.DoWork<DateTime>(dt => dt.TimeOfDay);
service.DoWork<DateTime>(dt => dt.Second);
}
}
interface IService
{
void DoWork<TObject, TProperty>(Expression<Func<TObject, TProperty>> propertySelector);
}
}
您可以通过明确写入 lambda 参数的类型来让它“推断”两个泛型参数:
service.DoWork((DateTime dt) => dt.Ticks);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.