调用带有不同参数的方法
本文关键字:参数 方法 调用 | 更新日期: 2023-09-27 18:10:18
我正在尝试使用不同的参数调用几个方法。例如,我有一个想要移动和删除的元素。在它的类中,我实现了这些方法:
public void Move(params object[] args)
{
Point lastpoint = (Point)Convert.ChangeType(args[0], typeof(Point));
Point newpoint = (Point)Convert.ChangeType(args[1], typeof(Point));
double left = Canvas.GetLeft(this) + (newpoint.X - lastpoint.X);
double top = Canvas.GetTop(this) + (newpoint.Y - lastpoint.Y);
Canvas.SetLeft(this, left);
Canvas.SetTop(this, top);
}
public void Remove(params object[] args)
{
Canvas parent = this.Parent as Canvas;
parent.Children.Remove(this);
}
地点:
- Move中的
- 参数由两个点组成
- Remove中的参数应该为null
我使用一个类来收集来自不同来源(鼠标,触摸,LeapMotion…)的所有事件,称为EventLinker。它非常简单,因为它只包含一个enum:
public enum GestureKey
{
OnClick,
OnDoubleClick,
OnLongClick,
OnRightClick,
OnDoubleRightClick,
OnLongRightClick,
OnMove
};
我可以在字典中使用:
private Dictionary<GestureKey, Action<object[]>> MyDictionary;
Move和Remove方法与两种不同的手势相关联:
MyDictionary.Add(GestureKey.OnRightClick, Remove);
MyDictionary.Add(GestureKey.OnMove, Move);
我们的想法是在几个监听器中使用这个字典,这些监听器附加到同一个UIElement,以便能够使用鼠标,触摸屏,LeapMotion…来控制我的申请。举个例子,当我检测到鼠标的侦听器中的点击时,我调用字典中的OnClick方法:
if (MyDictionary.ContainsKey(GestureKey.OnClick))
{
object[] args = { _lastPoint };
Application.Current.Dispatcher.BeginInvoke(MyDictionary[GestureKey.OnClick], args);
}
它不应该是一个问题,如果我所有的方法将包含相同的参数数量和类型,但在这里我有一个转换问题,但这个解决方案不是很干净,我确信有一种方法来做到这一点,就像我想。
我想以同样的方式调用我的方法,即使它们有不同的原型。如果有人知道怎么做,告诉我!
编辑:我认为问题是我用来链接我的方法与枚举的字典。它必须包含具有相同原型的方法。我是否可以使用任何类来做同样的事情,而不会出现相同的原型问题?
EDIT2:理想情况下,我应该有
public void Move(Point lastpoint, Point newpoint)
{
double left = Canvas.GetLeft(this) + (newpoint.X - lastpoint.X);
double top = Canvas.GetTop(this) + (newpoint.Y - lastpoint.Y);
Canvas.SetLeft(this, left);
Canvas.SetTop(this, top);
}
public void Remove()
{
Canvas parent = this.Parent as Canvas;
parent.Children.Remove(this);
}
问题,我认为,是我用来链接我的方法到一个GestureKey(见上文)的字典。
private Dictionary<GestureKey, Action<object[]>> MyDictionary;
dictionary类允许我将enum与任何类型链接起来,这里是Action。然而,我必须指定我的Action采用的参数,这对我来说是一个动态值。我想我应该这样做:
private Dictionary<GestureKey, Action<TYPELIST>> MyDictionary;
但我不知道如何拥有它。我试图使用列表,但我有同样的问题,它要求我静态的东西。应该动态地通知TYPELIST。我不知道Dictionary类是否适合做这个,也许有更好的类
这里的标记略有不同,但您都可以理解。下面是我的工作:
Dictionary<string, Delegate> _callbacks = new Dictionary<string, Delegate>();
public MainWindow()
{
InitializeComponent();
_callbacks.Add("move", new Action<Point, Point>(Move));
_callbacks.Add("remove", new Action(Remove));
Application.Current.Dispatcher.BeginInvoke(_callbacks["move"], new Point(5, 6), new Point(1, 3));
Application.Current.Dispatcher.BeginInvoke(_callbacks["remove"]);
}
public void Move(Point something1, Point something2)
{
}
public void Remove()
{
}