c# - C#错误: The contextual keyword 'var' may only appear within a local variable declaration

标签 c# winforms compiler-errors var

我编写了以下函数来创建axWindowsMediaPlayer播放列表:

WMPLib.IWMPPlaylist p2 = axWindowsMediaPlayer.playlistCollection.newPlaylist("Playlist 1");

private void CreatePlaylist(string _currentId)
{
  string selectedElementPageTypeValue = MainContentAreaBl.GetSelectedElementPageTypeValue(_currentId);
  var selectedElementJumpToValue = MainContentAreaBl.GetSelectedElementValue(_currentId, "jumpTo");
  if (selectedElementJumpToValue != null)
  {
     _currentId = selectedElementJumpToValue;                
     if (_currentId != null && _currentId != "menu" && selectedElementPageTypeValue == "video")
     {
        var playerFile = Path.Combine(Common.ContentFolderPath, MainContentAreaBl.GetSelectedElementDataPathValue(_currentId));
        p2.appendItem(axWindowsMediaPlayer.newMedia(playerFile));
        axWindowsMediaPlayer.currentPlaylist = p2;
        CreatePlaylist(_currentId);
     }                
     axWindowsMediaPlayer.Ctlcontrols.play();
  }
}

这里var p2在类级别声明。编译应用程序时,收到以下错误消息:

The contextual keyword 'var' may only appear within a local variable declaration



但是,我无法将var p2 = axWindowsMediaPlayer.playlistCollection.newPlaylist("Playlist 1");放在递归函数中,因为它将在每次迭代时创建新的播放列表。

如何在我的函数中访问p2?

编辑1:我在“输出”窗口中看到了

COM Reference 'WMPLib' is the interop assembly for ActiveX control 'AxWMPLib' but was marked to be linked by the compiler with the /link flag. This COM reference will be treated as a reference and will not be linked.



另外,现在它在axWindowsMediaplayer上显示以下错误:

A field initializer cannot reference the non-static field, method or property



此信息与我看到的错误有什么关系吗?如何解决这个问题?

最佳答案

您将必须使用正确的类型声明它,而不是使用var:

AxWMPLib.IWMPPlaylist p2 = axWindowsMediaPlayer.playlistCollection.newPlaylist("Playlist 1");
var仅允许用于局部变量,而不能用于字段,这就是错误消息告诉您的内容。该错误消息并不意味着该字段在错误的位置声明,您只是对字段类型使用了错误的语法。

关于c# - C#错误: The contextual keyword 'var' may only appear within a local variable declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34808300/

相关文章:

c# - 在多个函数之间使用对象

c# - 如何在 TreeView 控件中显示滚动条

java - 为什么此代码段显示编译错误?

c# - 授予非管理员用户访问权限以启动/停止服务 Windows 7

c# - 将命令文本转换为已回答问题中的字符串问题

c# - 如何通过 HTTP 从 C# 应用程序连接到 SQL Server?

C# Winforms 动态菜单条目

compiler-errors - Gulp Sass 编译错误

types - arc4random() 的余数运算符和数组的计数导致 "could not find an overload"错误

c# - 将 List<int> 分配给 IEnumerable<int> 是否有益?