gpt4 book ai didi

c# - 如何在自己的代码中模仿(单参数)重载决议规则?

转载 作者:太空宇宙 更新时间:2023-11-03 12:01:09 24 4
gpt4 key购买 nike

我有一个任意的对象实例,它可以实现接口(interface)和/或从​​类型层次结构继承。

我有一组接受单个输入参数的worker(由 DI 注入(inject))。

我可以减少到单个输入 System.TypeSystem.Type 的数组作为候选。

是否存在一些框架代码(或者可能是 Roslyn NuGet 包中的函数)应用与重载解析相同的规则,并且返回给定集的匹配类型或不明确的异常?

例如,如果我的实例是 DirectoryInfo 类型,则可以使用为 FileSystemInfo(DirectoryInfo 的基类)设计的工作程序,但是仅当不存在 DirectoryInfo 类型的工作人员时。

当然,我可以沿着 BaseTypes 层次结构走下去,但我也想考虑接口(interface)(包括 co(ntra)variance)。我真的不想重新发明那个轮子,然后因为我创建了自己的个人规则集而让其他开发人员感到沮丧。

最佳答案

一组Type您可能会发现对您的情况有用的扩展方法:

public static class TypeExtensions
{
public static bool IsAssignableToType(this Type derivedType, Type baseType)
{
bool retVal = baseType.IsAssignableFrom(derivedType) ||
(baseType.IsGenericType && derivedType.IsAssignableToGenericType(baseType)) ||
(baseType.IsInterface && (Nullable.GetUnderlyingType(derivedType)?.IsAssignableToType(baseType) ?? false));
return retVal;
}

private static bool IsAssignableToGenericType(this Type derivedType, Type genericBaseType)
{
var interfaceTypes = derivedType.GetInterfaces();

foreach (var it in interfaceTypes)
{
if (it.IsGenericType && it.GetGenericTypeDefinition() == genericBaseType)
return true;
}

if (derivedType.IsGenericType && derivedType.GetGenericTypeDefinition() == genericBaseType)
return true;

Type baseType = derivedType.BaseType;
if (baseType == null) return false;

return IsAssignableToGenericType(baseType, genericBaseType);
}
}

然后调用:

var isWorkerSuitableForObj = yourObjectInstance.GetType().IsAssignableToType(yourWorkerType)

这也适用于泛型,甚至适用于通用开放类型(例如 IEnumerable<>)。

关于c# - 如何在自己的代码中模仿(单参数)重载决议规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56937564/

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