【C#】WinForm開發(fā)的小技巧(2)——命令行

.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)一下喜歡,讓更多的人看到

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,535評(píng)論 19 139
  • 又是一個(gè)月考結(jié)束,幾人歡喜幾人憂!看到好幾個(gè)連續(xù)兩次考試進(jìn)步的孩子,真的替他們高興。又感覺到好幾個(gè)連續(xù)落后的,擔(dān)心...
    滌冰閱讀 452評(píng)論 0 0
  • 我是一個(gè)很喜歡說卻不又不喜歡做的人,由于頭發(fā)稀疏,前額老是被吐槽很禿,總是怕自己嫁不出去,于是我把頭發(fā)給剪短了。 ...
    鄧地瓜閱讀 360評(píng)論 0 0

友情鏈接更多精彩內(nèi)容