gpt4 book ai didi

c# - IsAssignableFrom 的隐式版本?

转载 作者:太空狗 更新时间:2023-10-29 21:31:21 25 4
gpt4 key购买 nike

在我写的使用反射的代码中

if (f.FieldType.IsAssignableFrom("".GetType()))

我有一个隐式转换为字符串的类。但是上面的 if 语句没有捕捉到它。如何通过隐式字符串转换进行反射/上述 if 语句捕获字符串和类?而不是特定的字符串和我知道的每个类?

最佳答案

我会使用一个扩展方法,它获取所有公共(public)静态方法并检查具有正确名称和返回类型的方法。

public static class TypeExtentions
{
public static bool ImplicitlyConvertsTo(this Type type, Type destinationType)
{

if (type == destinationType)
return true;


return (from method in type.GetMethods(BindingFlags.Static |
BindingFlags.Public)
where method.Name == "op_Implicit" &&
method.ReturnType == destinationType
select method
).Count() > 0;
}
}

关于c# - IsAssignableFrom 的隐式版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2075471/

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