CSharp随笔-癫疯之作

181 字
1 分钟
CSharp随笔-癫疯之作

起因是写了这样一段代码

if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
string ipString = string.Join(",", e.NewItems.Cast<IWebSocketConnection>().Select(x => x.ConnectionInfo.ClientIpAddress));
WeakReferenceMessenger.Default.Send<DisplayAlertMessage>(new("有新用户连接", ipString));
}
else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
string ipString = string.Join(",", e.OldItems.Cast<IWebSocketConnection>().Select(x => x.ConnectionInfo.ClientIpAddress));
WeakReferenceMessenger.Default.Send<DisplayAlertMessage>(new("有用户断开连接", ipString));
}
else
{
throw new InvalidOperationException("不支持此类操作");
}

这里显然是可以复用一下的 而我又正好想到了C#的新特性 模式匹配
于是有了下面这段@#%&%%&#@%&

WeakReferenceMessenger.Default.Send<DisplayAlertMessage>(((Func<(string, System.Collections.IList), (string, string)>)(t => (t.Item1, string.Join(",", t.Item2.Cast<IWebSocketConnection>().Select(x => x.ConnectionInfo.ClientIpAddress)))))(e.Action switch
{
System.Collections.Specialized.NotifyCollectionChangedAction.Add => ("有新用户连接", e.NewItems),
System.Collections.Specialized.NotifyCollectionChangedAction.Remove => ("有用户断开连接", e.OldItems),
_ => throw new InvalidOperationException("不支持此类操作")
}).ToDisplayAlertMessage());
internal static class ValueTupleExtensions // C#不能把Tuple展开成多个参数 :(
{
public static DisplayAlertMessage ToDisplayAlertMessage(this ValueTuple<string, string> tuple)
{
return new DisplayAlertMessage(tuple.Item1, tuple.Item2);
}
}

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或打赏支持!

打赏
CSharp随笔-癫疯之作
https://blog.truebigsand.top/posts/csharp-notes-crazy/
作者
真-大沙子
发布于
2023-07-13
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
真-大沙子
编程 · 数学 · 二次元 · 生活
公告
音乐
封面

音乐

暂未播放

0:000:00
暂无歌词
分类
标签
站点统计
文章
45
分类
5
标签
51
总字数
42,438
运行时长
0
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.13.5
文章许可
CC BY-NC-SA 4.0

文章目录