繁体   English   中英

可以从表达式参数推断其类型参数的 C# 通用方法

[英]C# Generic method that can infer its type argument from expression parameter

我正在尝试创建一个方法,该方法可以接受对象类型作为类型参数,以及对对象属性之一的引用及其类型。 像这样:

service.DoWork<DateTime>(dt => dt.Ticks)

我查看了其他库是如何做这些事情的,最终得到了以下定义:

interface IService
{
    void DoWork<TObject, TProperty>(Expression<Func<TObject, TProperty>> propertySelector);
}

理想情况下,用户可以传入一种类型的对象,然后使用表达式“选择”其每个属性。 我的方法然后可以知道所选表达式,以及它的类型对象类型

  service.DoWork<DateTime>(dt => dt.Ticks);
  service.DoWork<DateTime>(dt => dt.TimeOfDay);
  service.DoWork<DateTime>(dt => dt.Second);

但是,以这种方式调用该方法会导致以下错误:

Using the generic method 'IService.DoWork<TObject, TProperty>(Expression<Func<TObject, TProperty>>)' requires 2 type arguments

如果我指定属性的类型,那么一切正常:

  service.DoWork<DateTime, long>(dt => dt.Ticks);
  service.DoWork<DateTime, TimeSpan>(dt => dt.TimeOfDay);
  service.DoWork<DateTime, int>(dt => dt.Second);

但是,这似乎是多余的。 编译器可以从我提供的表达式参数中提取类型,据我所知,很多其他库使用这种类型推断来提供干净的接口(Linq、MOQ、FluentAssertions 等等)

我想我需要以某种方式更改我的方法定义,但我似乎无法找到正确的方法来做到这一点。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM