C# 返回基于类型的委托函数

C# 返回基于类型的委托函数,c#,C#,具有以下代码: public delegate Task<bool> CreateObject<TU> (TU obj, object parameters, Expression<Func<TU, object[]>> includes = null); // This Version compile public CreateObject<Dummy> Example1(Type listOfType) { C

具有以下代码:

public delegate Task<bool> CreateObject<TU>
      (TU obj, object parameters, Expression<Func<TU, object[]>> includes = null);

// This Version compile
public CreateObject<Dummy> Example1(Type listOfType)
{
    CreateObject<Dummy> c = DummyRepository.InsertAsync;
    return c;
}

// This Version do NOT compile    
public CreateObject<TU> Example2<TU>(Type listOfType)
{
    if (listOfType == typeof(Dummy)) return DummyRepository.InsertAsync;
    if (listOfType == typeof(DummyName)) return DummyNameRepository.InsertAsync;
    if (listOfType == typeof(DummyEntry)) return DummyEntryRepository.InsertAsync;
    return null;
}
// This Version do NOT compile    
public CreateObject<TU> Example3<TU>()
{
    if (typeof(TU) == typeof(Dummy)) return DummyRepository.InsertAsync;
    if (typeof(TU) == typeof(DummyName)) return DummyNameRepository.InsertAsync;
    if (typeof(TU) == typeof(DummyEntry)) return DummyEntryRepository.InsertAsync;
    return null;
}
这行代码可以编译,但不起作用


还有其他选择吗?我有什么样的其他设计模式或解决方案?

我找到了一个可行的解决方案:

public dynamic Example7(Type listOfType)
{
    CreateObject<Dummy> a1 = DummyRepository.InsertAsync;
    if (listOfType == typeof(Dummy)) return (CreateObject<Dummy>)DummyRepository.InsertAsync;
    if (listOfType == typeof(DummyName)) return (CreateObject<DummyName>)DummyNameRepository.InsertAsync;
    if (listOfType == typeof(DummyEntry)) return (CreateObject<DummyEntry>)DummyEntryRepository.InsertAsync;
    return null;
}

它正在发挥作用。。。。我仍然没有做任何性能/速度测试,但至少代码正在做我想要的

未编译的版本不会创建委托。。。第一个将是,因为您正在显式地创建委托。您不能对泛型类型应用运行时逻辑。@Ankur是的,我明白了,但是我还需要什么解决方案来实现我想要的目的呢?您可以使用接口,即创建接口,为所有3种情况实现接口,并将接口用作Example2函数的返回类型经验法则:如果您的泛型类型必须测试其泛型参数的类型,那么(至少对我来说)这是泛型被误用的强烈指示。
public dynamic Example7(Type listOfType)
{
    CreateObject<Dummy> a1 = DummyRepository.InsertAsync;
    if (listOfType == typeof(Dummy)) return (CreateObject<Dummy>)DummyRepository.InsertAsync;
    if (listOfType == typeof(DummyName)) return (CreateObject<DummyName>)DummyNameRepository.InsertAsync;
    if (listOfType == typeof(DummyEntry)) return (CreateObject<DummyEntry>)DummyEntryRepository.InsertAsync;
    return null;
}
var rep = uow.Example7(listOfType);
foreach (var t in list as dynamic)
{
   .....
   var res = await rep(t, null, null);