采用 List[] 的操作委托存在问题
我有一个像这样声明的操作委托。
private readonly Action<List<PSDPoint>[]> _psdAction;
_psdAction = AddPSDData;
PSDPoint 是一个非常简单的类。
public class PSDPoint
{
public int Frequency { get; set; }
public double Power { get; set; }
}
我正在尝试这样称呼代表。
private void PSDData(object sender, PSDEventArgs e)
{
Dispatcher.Invoke(_psdAction, e.Data);
}
PSDEventArgs 看起来像这样。可以看到e.Data是相同的数据类型。
public class PSDEventArgs
{
public List<PSDPoint>[] Data { get; set; }
public string[] Channels { get; set; }
}
_psdAction 指向这个函数。我从来没有达到这个代码。
private void AddPSDData(List<PSDPoint>[] data)
{
...
}
我收到此错误,调度程序正在尝试调用。我不明白为什么。我正在传递正确的类型。我猜拥有一系列列表会有些“时髦”吗?
Object of type 'System.Collections.Generic.List`1[DataLogger.Model.PSDPoint]' cannot be converted to type 'System.Collections.Generic.List`1[DataLogger.Model.PSDPoint][]'.
I have an Action delegate declared like this.
private readonly Action<List<PSDPoint>[]> _psdAction;
_psdAction = AddPSDData;
PSDPoint is a very simple class.
public class PSDPoint
{
public int Frequency { get; set; }
public double Power { get; set; }
}
I am attempting to call the delegate like this.
private void PSDData(object sender, PSDEventArgs e)
{
Dispatcher.Invoke(_psdAction, e.Data);
}
PSDEventArgs looks like this. You can see e.Data is the same data type.
public class PSDEventArgs
{
public List<PSDPoint>[] Data { get; set; }
public string[] Channels { get; set; }
}
_psdAction points to this function. I never reach this code.
private void AddPSDData(List<PSDPoint>[] data)
{
...
}
I get this error the dispatcher is attempting to invoke. I can't figure out why. I'm passing in the right type. I'm guessing it's something "funky" with having an array of Lists?
Object of type 'System.Collections.Generic.List`1[DataLogger.Model.PSDPoint]' cannot be converted to type 'System.Collections.Generic.List`1[DataLogger.Model.PSDPoint][]'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请尝试以下
操作 问题是
Invoke
的第二个参数采用params object[]
。这样做的目的是支持具有可变数量参数的委托。数组的内容映射到参数。第一个元素指向第一个参数,第二个元素指向第二个参数,依此类推。当您使用
e.Data
调用它时,C# 编译器会看到一个数组。它没有将数组作为第一个参数传递,而是尝试将每个元素作为参数传递。通过转换为object
,您可以强制编译器将其解释为单个参数Try the following
The problem is that the second parameter of
Invoke
takes aparams object[]
. The intent of this is to support delegates with variable number of arguments. The contents of the array are mapped to parameters. First element going to the first parameter, second element to the second parameter and so on.When you call it with
e.Data
the C# compiler sees an array. Instead of passing the array as the first argument it tries to pass each element as a parameter. By casting toobject
you can force the compiler to interpret it as a single parameter你必须调用
因为 Invoke 需要一个包含所有参数的数组 - 请参阅此处
you have to call
Because Invoke wants an array with all the parameters - see here