求教 C#类的初始化变量问题

2020-10-23 23:20:05 +08:00
 crella

在外部代码怎么用 Ngan.re_dict 来访问 Ngan 类的 Dictionary<string, Regex> redict (也需要这样来访问 Ngan.re_funcs),初衷是在某些流程里减少重复生成正则表达式。最好还是用 Dictionary 方式来储存(其他的不会...)

public class Ngan
	{

		public static Dictionary<Regex, Func<string, string>> re_funcs;
		public static Dictionary<string, Regex> re_dict;
		public Ngan()
		{
	
			// 读取正则表达式到缓存
			load_re_dict();
			load_re_funcs();
		}
		
		private static void load_re_dict(){
			re_dict = new Dictionary<string, Regex>();
			Regex quote_re = new Regex(@"\[quote\](.*?)\[\/quote\]", RegexOptions.Multiline);
			Regex uid_re = new Regex(@"\[uid.*?\](.*?)\[\/uid\]");
			Regex quoted_re = new Regex(@"\[\/b\](.*?)\[\/quote\]", RegexOptions.Multiline);
			Regex collapse_re = new Regex(@"\[collapse(=.*?)\](.*?)\[\/collapse\]", RegexOptions.Multiline);
			
			re_dict["quote"] = quote_re;
			re_dict["uid"] = uid_re;
			re_dict["quoted"] = quoted_re;
			re_dict["collapse"] = collapse_re;
		}
		
		private static void load_re_funcs(){
			
			re_funcs = new Dictionary<Regex, Func<string, string>>();
			// 处理回复内容

			Regex reply_re = new Regex(@"Reply\sto.*?\[uid.*?\](.*?)\[\/uid\].*?\[\/b\]", RegexOptions.Multiline);
			Func<string, string> reply_act = (con) => String.Format( "<br><i><b>回复</b>{0}</i><br>", con);
			re_funcs.Add(reply_re, reply_act);
			
			// 链接
			Regex link_re = new Regex(@"\[url\](.*?)\[\/url\]");
			Func<string, string> link_act = (con) => {
				if (!con.StartsWith("http")){
					con = "http://" + con; // 自动添加 http://前缀
				}
				return ("<a href=\"" + con + "\" target=\"_blank\">链接</a>");
			};
			re_funcs.Add(link_re, link_act);
			
		}
// ...
	}
3290 次点击
所在节点    C#
4 条回复
geelaw
2020-10-23 23:27:24 +08:00
用静态构造器,具体来说把 public Ngan 改成 static Ngan 。
WeaPoon
2020-10-23 23:29:02 +08:00
貌似没明白你想问的,你是想问,不要总是初始化 load 么?
如果是这意思,可以用 public static Ngan(){} 只会初始化一次。
WeaPoon
2020-10-23 23:32:33 +08:00
1 楼说的对
lukaz
2020-10-23 23:33:34 +08:00
问题问的不是很清楚,但我猜你需要的是把构造方法变成 static 的

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/718044

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX