我试图用Delegate.CreateDelegate创建一个委托,我得到了错误:
ArgumentException:方法参数是不兼容的System.Delegate.CreateDelegate (System.Type类型,System.Object firstArgument,System.Reflection.MethodInfo方法,System.Boolean throwOnBindFailure,System.Boolean allowClosed) (at <6073cf49ed704e958b8a66d540dea948>:0) System.Delegate.CreateDelegate (System.Type type,System.Reflection.MethodInfo method,System.Boolean throwOnBindFailure) (at <6073cf49ed704e958b8a66d540dea948>:0) System.Reflection.MethodInfo (System.Type type,method) (在en20 20#)
这是我的密码:
for (int i = 0; i < statusMoves.Length; i++)
{
StatusMovesMethods moveMethods = new StatusMovesMethods();
MethodInfo theMethod = moveMethods.GetType().GetMethod(statusMoves[i].name);
moveMethod = (Move.MoveMethod)Delegate.CreateDelegate(typeof(Move.MoveMethod), theMethod);
statusMoves[i].moveMethod = moveMethod;
}
这就是初始化moveMethod的地方。
public delegate void MoveMethod(Battler target);
public MoveMethod moveMethod;
发布于 2022-05-02 09:19:37
所以,我仍然不知道它为什么会给我一个错误,但我找到了一种方法来修复它,我发现This post中有人有类似的问题,然后我使用了下面的代码:
void Start()
{
for(int i = 0; i < statusMoves.Length; i++)
{
statusMoves[i].moveMethod = GetByName(moveMethods, statusMoves[i].name);
}
}
static Action GetByName(object target, string methodName)
{
MethodInfo method = target.GetType()
.GetMethod(methodName,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
// Insert appropriate check for method == null here
return (Action)Delegate.CreateDelegate
(typeof(Action), target, method);
}
希望这能帮到别人
https://stackoverflow.com/questions/72075156
复制相似问题