拥有以下代码:
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;
}
我正在尝试返回一个方法(基于T的所有共享签名),但是,我在编写此代码时遇到问题,有人知道该怎么做吗?
我需要的解决方案必须基于Example2,我使用Type listOfType
,因此我想避免调用通用TU的方法......
更新:#1
if (listOfType == typeof(Dummy)) return (CreateObject<object>)(object)(CreateObject<Dummy>)DummyRepository.InsertAsync;
这一行,编译,但不起作用......
还有其他选择吗?我有什么样的其他设计模式或解决方案?
答案 0 :(得分:0)
我找到了一个有效的解决方案:
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;
}
然后,在解决方案资源管理器窗口中,右键单击引用,选择添加引用,转到.NET选项卡,查找并添加Microsoft.CSharp。
&#34;消费者类&#34;会有类似的东西:
var rep = uow.Example7(listOfType);
foreach (var t in list as dynamic)
{
.....
var res = await rep(t, null, null);
它正在工作......我仍然没有进行任何性能/速度测试,但至少代码正在做我想要的......