gpt4 book ai didi

c# - Func 委托(delegate)声明的方法

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:23 25 4
gpt4 key购买 nike

在非泛型类中声明这两个方法,它们共享相同的签名:

    private TypeResolverResult<T> TryRetrieveFromReusable<T>(TypeResolverConfiguration<T> typeResolverConfiguration) where T : class 
{
return null;
}

private TypeResolverResult<T> BuildNew<T>(TypeResolverConfiguration<T> typeResolverConfiguration) where T : class
{
return null;
}

如何创建代表这些方法签名的委托(delegate)?

我好像无法理解,我试过了:

    private Func<TypeResolverConfiguration<T>, TypeResolverResult<T>> _typeResolveFunc;

但显然这行不通,因为该类是非泛型的,我无法更改它。

谢谢

更新

这或多或少是我需要的:

    public class Manager : ATypeResolver, IManager
{
private neeedDelegate;


public Manager(RuntimeConfiguration runtimeConfiguration, IList<RepositoryContainer> repositories)
{
if (runtimeConfiguration.WhatEver)
{
neeedDelegate = TryRetrieveFromReusable;
}
else
{
neeedDelegate = BuildNew;
}
}

public override TypeResolverResult<T> Resolve<T>() where T : class
{
//Want to avoid doing this:

if (runtimeConfiguration.WhatEver)
{
TryRetrieveFromReusable(new TypeResolverConfiguration<T>());
}
else
{
BuildNew(new TypeResolverConfiguration<T>());
}

//and have just this

neeedDelegate<T>(new TypeResolverConfiguration<T>());
}

private TypeResolverResult<T> TryRetrieveFromReusable<T>(TypeResolverConfiguration<T> typeResolverConfiguration) where T : class
{
return null;
}

private TypeResolverResult<T> BuildNew<T>(TypeResolverConfiguration<T> typeResolverConfiguration) where T : class
{
return null;
}
}

最佳答案

更新 据我所知,只要ATypeResolver,像这样的方法应该可行。有一个 where T : classResolve<T> :

public class Manager : ATypeResolver, IManager
{
private bool tryRetrieveFromReusable;

public Manager(RuntimeConfiguration runtimeConfiguration, IList<RepositoryContainer> repositories)
{
this.tryRetrieveFromReusable = runtimeConfiguration.WhatEver;
}
public override TypeResolverResult<T> Resolve<T>()
{
var typeResolver = tryRetrieveFromReusable ? (TypeResolver<T>)TryRetrieveFromReusable : BuildNew;

return typeResolver(new TypeResolverConfiguration<T>());
}
}

这使用自定义委托(delegate)类型(一个 Func 就像你应该工作一样):

public delegate TypeResolverResult<T> TypeResolver<T>(
TypeResolverConfiguration<T> typeResolverConfiguration) where T : class;

喜欢的可以移步var typeResolver = ...行到它自己的方法,以分离逻辑并允许您使用它而不仅仅是 Resolve .如果这样做,Resolve 可能会像这样简单:return GetTypeResolver<T>()(new TypeResolverConfiguration<T>()); .

关于c# - Func 委托(delegate)声明的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com