作者james999 (无伤大雅)
看板C_Sharp
标题[问题] 网路上代码问题请益
时间Thu Feb 1 18:08:00 2018
小弟是C#新手,有小段从网上找到的代码,
不过不太清楚是干嘛的,找了一堆关於委派及事件的资讯,
也没看过这样的写法,想请板友指导,谢谢。
mediaPlayer.EndReached += (sender, e) => {
playFinished = true;
};
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 220.132.128.217
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/C_Sharp/M.1517479683.A.F41.html
1F:推 vi000246: 你都知道是委派跟事件了 为什麽会看不懂? 02/01 20:21
2F:→ testPtt: 就跟可视元件事件点两下填入playFinished = true;一样 02/01 20:25
3F:推 gn1943141: lambda 02/01 20:37
4F:推 lightyen: 订阅事件的一种简便写法 如果不需要取消订阅的话就能这 02/02 00:18
5F:→ lightyen: 样写 02/02 00:18
6F:→ lightyen: 缺点是sender,e在同一个域只能有一个 02/02 00:21
7F:→ lightyen: 可以另改名称: (a, b) => {...} 02/02 00:22
谢谢大家的回覆,只知道这看起来像callback function,但是没这样写过。
不好意思,有个部份想再请教一下…
其实代码主要是参考Vlc.Net,如下:
--我是分隔线--
using System;
using System.IO;
using System.Threading;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string libDirectory;
if (IntPtr.Size == 4)
{
// Use 32 bits library
libDirectory = Path.Combine(Environment.CurrentDirectory,
"libvlc_x86");
}
else
{
// Use 64 bits library
libDirectory = Path.Combine(Environment.CurrentDirectory,
"libvlc_x64");
}
var options = new string[]
{
// VLC options can be given here. Please refer to the VLC
command line documentation.
};
var mediaPlayer = new Vlc.DotNet.Core.VlcMediaPlayer(new
DirectoryInfo(libDirectory));
var mediaOptions = new string[]
{
":sout=#file{dst="+Path.Combine(Environment.CurrentDirectory,
"output.mov")+"}",
":sout-keep"
};
mediaPlayer.SetMedia(new
Uri("
http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_h264.mov"),
mediaOptions);
bool playFinished = false;
mediaPlayer.PositionChanged += (sender, e) =>
{
Console.Write("\r" + Math.Floor(e.NewPosition * 100) + "%");
};
mediaPlayer.EncounteredError += (sender, e) =>
{
Console.Error.Write("An error occurred");
playFinished = true;
};
mediaPlayer.EndReached += (sender, e) => {
playFinished = true;
};
mediaPlayer.Play();
// Ugly, sorry, that's just an example...
while(!playFinished)
{
Thread.Sleep(TimeSpan.FromMilliseconds(500));
}
}
}
}
--我是分隔线--
问题1.
mediaPlayer.PositionChanged += (sender, e) =>
这个部份是先告知事件触发的话,就来执行事件委派的内容,
只是函式内容直接写在里面了?
问题2.
如上将Main的内容改为副程式,可能此副程式同时会被呼叫多次,
接收参数为一个识别字串,并建立Dictionary容器,
key为识别字串,而value为mediaPlayer的实例,
请问这样会有问题吗? 因为副程式内的区域变数playFinished,
在副程式结束後就应该要消失了,不过不明白的是…
实际这麽做了後,程式能正常运行,主要是这点觉得奇怪。
以上两个重要观念问题再麻烦大家协助回覆哦,谢谢你们:)
※ 编辑: james999 (220.132.128.217), 02/05/2018 16:40:29