项目场景:
我在写一个点胶机的胶线编辑器时,需要实现一个撤销重做的功能。问题描述:
,在C#中使用反射方式实现传参,参数为object,要转换参数时需要使用IEnumerable,不然取不到想要的值。
参数委托端:
//获取方法信息 执行反命令
MethodInfo methodInfo =info.Target.GetType().GetMethod(x.Value.UnName);
ParameterInfo[] p = methodInfo.GetParameters();
if (p.Count() != 0)
{
methodInfo.Invoke(info.Target, x.Value.Paras);
参数接收端:
if (tObj is Array)
{
foreach (object obj in (**IEnumerable**)tObj)
{
#region 简单参数
[UnRedo(UnCmd = nameof(UnAddCommand), UnRedoInfoType = UnRedoInfoType.Cmd)]
public void AddCommand(object nPathPointsScale)
{
object tObj = nPathPointsScale;
object tVel = null;
if (tObj is Array)
{
foreach (object obj in (IEnumerable)tObj)
{
Delegate_UpdateMsg("重做");
tVel = obj;
AddPathPointToPathPointsScaleList((BaseClass)tVel);
}
}
else
{
AddPathPointToPathPointsScaleList((BaseClass)tObj);
}
}
[UnRedo(UnCmd = nameof(AddCommand), UnRedoInfoType = UnRedoInfoType.Cmd)]
public void UnAddCommand(object nPathPointsScale)
{
object tObj = nPathPointsScale;
object tVel = null;
if (tObj is Array)
{
foreach (object obj in (IEnumerable)tObj)
{
tVel = obj;
}
for (int i = 0; i < mPathDataScaleList.Count; i++)
{
List<BaseClass> tList = mPathDataScaleList[i];
for (int j = 0; j < tList.Count; j++)
{
if (tList[j].GetType() == tVel.GetType())
{
Delegate_UpdateMsg("撤销");
mPathDataScaleList[i].Remove((BaseClass)tVel);
ClearZeroCountPathList();
}
}
}
}
}
#endregion
解决方案:
在反函数中,参数接收端传入的参数,其实是Array类型的object对象,需要直接强制转换(Array)tObj是不行的,需要将它进行强制迭代,如下代码所示才可获得所需的值。foreach (object obj in (IEnumerable)tObj)
{
tVel = obj;
}