gpt4 book ai didi

c# - 在 C# 中使用反射获取具有单个属性或没有属性的方法

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

我正在学习反射,我正在研究一种可序列化的操作类型,它可以保存,然后加载和触发。可序列化操作支持不带参数或类型为 int、float、double、string 或 bool 的单个参数的方法。

所有传递名称的方法要么具有上面列出的类型的一个属性,要么根本没有没有属性也有一个具有默认值的属性。我的问题来了。首先,当我为具有重载的方法调用 target.GetType().GetMethod(methodName); 时,我得到一个 AmbiguousMatchException,如果我为具有单个可选的方法调用它,我得到一个 NULL范围。

所以我现在做的是从 try-catch 开始捕捉 AmbiguousMatchException,然后告诉我给定的方法有重载。如果出现异常,我将开始尝试获取传递不同属性类型数组的方法以进行搜索:

public static MethodInfo GetMethod(string methodName, Object _target)
{
try
{
MethodInfo info = _target.GetType().GetMethod(methodName);
return info;
}
catch (AmbiguousMatchException ex)
{
MethodInfo info = _target.GetType().GetMethod(methodName, new System.Type[0]);
if (info != null) return info;
info = _target.GetType().GetMethod(methodName, new[] { typeof(int) });
if (info != null) return info;
info = _target.GetType().GetMethod(methodName, new[] { typeof(float) });
if (info != null) return info;
info = _target.GetType().GetMethod(methodName, new[] { typeof(double) });
if (info != null) return info;
info = _target.GetType().GetMethod(methodName, new[] { typeof(string) });
if (info != null) return info;
info = _target.GetType().GetMethod(methodName, new[] { typeof(bool) });
return info;
}
}

这非常丑陋,但它适用于重载方法。但是,如果该方法具有可选参数,则返回 NULL。我尝试使用 OptionalParamBinding 绑定(bind)标志,但即使对于没有重载和单个可选参数的方法,它也返回 NULL。

所以我的问题是:我该怎么做?我需要这个静态方法来找到: - 使用 int、float、double、string 或 bool 参数重载方法 - 如果失败,则使用可选的 int、float、double、string 或 bool 参数重载 - 如果失败,不带任何参数的重载

最佳答案

对于您的特定要求,在 LINQ 查询中很容易做到这一点。

var validParameterTypes = new HashSet<Type> { typeof(int), typeof(float), ... };

var methods = from method in _target.GetType().GetMethods()
let parameters = method.GetParameters()
let hasParameters = parameters.Length > 0
let firstParameter = hasParameters ? parameters[0] : null
let isOptionalParameter = (hasParameters && firstParameter.IsOptional) ? true : false
where method.Name == methodName &&
(!hasParameters || validParameterTypes.Contains(firstParameter.ParameterType))
orderby parameters.Length descending, isOptionalParameter
select method;

此时您可以评估查询中的方法,看看它们是否满足您的需求。

不过,还有一个不同的问题,那就是“我应该这样做吗?”。 TyCobb 已经在他的评论中提到了这一点,他是对的。

您目前尝试做事的方式是大量工作,但没有立竿见影的效果。所以你得到了一个重载列表,这对你没有真正的帮助。现在您必须自己进行重载解析并找到要调用的“最佳”重载(或者只采用您找到的第一个重载,但如果添加/删除/更改方法,它很容易中断)。

假设您还存储了您要查找的参数类型(如果有)。知道这会将您的代码压缩为:

var parameterTypes = (knownParameterType == null ) ? Type.EmptyTypes : new[] { knownParameterType };
var method = _target.GetType().GetMethod(methodName, parameterTypes);

更简单、更清晰、更明显正确!您甚至不必在此处检查允许的参数类型,让它们作为构建您正在定义的有效“操作类型”的一部分来执行此操作。

关于c# - 在 C# 中使用反射获取具有单个属性或没有属性的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37977691/

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