.NET Core 依賴注入改造(2)- 委托轉(zhuǎn)換
一、
winform開發(fā)或控制臺(tái)開發(fā)的時(shí)候,我們經(jīng)常希望自己的程序可以留一些小“后門”
或方便調(diào)試,或特殊需求,或僅為了好玩;
比如
我做了一個(gè)掃碼登錄的功能,但是處于測(cè)試狀態(tài),通過命令行打開此功能

二、
可能大家會(huì)覺得很簡單Environment.GetCommandLineArgs().Contains("--debug")不就行了嗎?
但是如果增加一個(gè)功能,比如這樣

所以我寫了一個(gè)解析命令行的類
三、
StartupCommands
static class StartupCommands
{
static StartupCommands()
{
try
{
var args = Environment.GetCommandLineArgs().Skip(1).ToArray(); // 去掉命令行第一個(gè)命令
foreach (var prop in typeof(StartupCommands).GetProperties())
{
// 循環(huán)當(dāng)前類的屬性, 優(yōu)先獲取 --{屬性全名,不區(qū)分大小寫} 如 --loginname
// 如果沒有取到, 再次獲取 -{短命令} 如 -n
var arg = args.FirstOrDefault(x => x.StartsWith($"--{prop.Name}", StringComparison.OrdinalIgnoreCase))
?? (Attribute.GetCustomAttribute(prop, typeof(ShortAttribute)) is ShortAttribute attr
? args.FirstOrDefault(x => x.StartsWith($"-{attr.Command}", StringComparison.Ordinal))
: null);
if (arg == null) // 都沒取到則忽略
{
continue;
}
// 獲取命令 冒號(hào)(:) 之后的內(nèi)容, 當(dāng)做屬性值, 如果不存在冒號(hào)
// 默認(rèn)值為true , 如: --debug 等于 --debug:true
var val = arg.Split(':').ElementAtOrDefault(1)?.Trim() ?? "true";
// 轉(zhuǎn)換類型并設(shè)置到屬性
prop.SetValue(null, Convert.ChangeType(val, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType));
}
}
catch (Exception ex)
{
System.Diagnostics.Trace.TraceError("SuperAddon初始化 異常", ex);
throw new NotSupportedException("啟動(dòng)參數(shù)有誤", ex);
}
}
/// <summary>
/// 短命令
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
sealed class ShortAttribute : Attribute
{
public ShortAttribute(string command) => Command = command;
public string Command { get; }
}
[Short("n")]
public static string LoginName { get; private set; }
[Short("p")]
public static string Password { get; private set; }
[Short("d")]
public static bool? Debug { get; private set; }
public static bool? AutoLogin { get; private set; }
}
基本規(guī)則是 --完整指令名[:值] 或 -短指令[:值]
完整指令名匹配 類中的屬性名稱(不區(qū)分大小寫)
短指令通過ShortAttribute來指定(區(qū)分大小寫)
值不存在時(shí)默認(rèn)為 true
四、
這樣用
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
if (StartupCommands.Debug == true)
{
pictureBox2.Visible = true;
}
textBox1.Text = StartupCommands.LoginName;
textBox2.Text = StartupCommands.Password;
}
protected override void OnShown(EventArgs e)
{
if (StartupCommands.AutoLogin == true)
{
button1.PerformClick();
}
base.OnShown(e);
}
private void pictureBox2_Click(object sender, EventArgs e)
{
groupBox1.Visible = false;
pictureBox1.Visible = false;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("登錄成功");
}
}
五、
嗯。。。就這么點(diǎn)。。。
如果文章可以幫到你,別忘了幫我點(diǎn)一下喜歡,讓更多的人看到
