- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个任意的对象实例,它可以实现接口(interface)和/或从类型层次结构继承。
我有一组接受单个输入参数的worker(由 DI 注入(inject))。
我可以减少到单个输入 System.Type
和 System.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/
tl;dr:我编写的函数创建了多个子进程,这些子进程在提交消息中的数据时解决 promise 。尽管该函数将所有这些 Promise 包装在 Promise.All 中,但该函数将突然返回,并且 Pr
我目前正在阅读 Jon Skeet 的 C# in depth 第 2 版,我想到了以下问题: 编译器如何能够在 list.Sort(Comparison) 之间进行选择?和 list.Sort(My
我是一名优秀的程序员,十分优秀!