【问题标题】:Pass string from a class as a method parameter in c#?将类中的字符串作为c#中的方法参数传递?
【发布时间】:2018-02-02 05:26:43
【问题描述】:

我对 C# 还是很陌生,并试图制定一种方法来更改列表视图通讯簿中的名称、地址等。

关于如何将“.Name”部分变成一个可以作为参数传递给方法的变量,我一直在摸不着头脑。

为了使我的方法起作用,我需要能够使用参数将“.Name”部分更改为:“.Address”、“.Phone”等。

Box1 表示禁用的文本框,仅显示有关列表视图中所选项目的信息。 Box2 表示用户可以在其中键入他想要进行的更改的框。

代码可以运行,这只是为了学习如何提高效率而不是重复。

private void CheckInput(string box1, string box2, string details)
    {
        if (box2 != box1 && box2 != "")                             
        {
            DialogResult dialogResult = MessageBox.Show(
                "Are you sure you want to change the " + details 
                + " from, " + box1 + ", to, " + box2 + "?", "Warning", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (dialogResult == DialogResult.Yes)
            {
                people[listView1.SelectedItems[0].Index].Name = box2;

                if (box2 == "")
                {
                    listView1.SelectedItems[0].Text = box1;
                }
                else
                {
                    listView1.SelectedItems[0].Text = box2;
                }
            }
            if (dialogResult == DialogResult.No)
            {

            }
        }
    }

    class Person
    {
        public string Name
        {
            get;
            set;
        }
        public string Email
        {
            get;
            set;
        }
        public string Address
        {
            get;
            set;
        }
        public string Phone
        {
            get;
            set;
        }

    }

【问题讨论】:

    标签: c#


    【解决方案1】:

    我会使用单独的名称和设置器委托:

    private void CheckInput(string oldValue, string newValue,
              string propertyName, Action<string> setterDelegate)
    {
        ...
        setterDelegate(newValue);
    }
    
    CheckInput("old", "new", nameof(value.Name), newVal => value.Name = newVal);
    

    如果您只想使用名称Set object property using reflection,也可以使用反射,但您仍然需要将“Person”作为参数传递。另一个更好的选择是使用表达式树,类似于 LINQ-to-SQL 设置查询并以这种方式获取属性名称的方式 - Retrieving Property name from lambda expression

    注意:通常框架提供它们自己的绑定值和验证机制。如果您需要练习重新发明轮子,请查看使用属性注释属性 - Validation using attributes(请小心,因为它包含完整的答案,因此您可能需要先阅读一般属性)。

    【讨论】:

    • 感谢您的快速回答。你的回答对我来说有点太复杂了,因为我对编程还是很陌生。如果您有时间,能否请您在字符串上使用与我相同的名称,或者更详细地解释您的示例代码?
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    相关资源
    最近更新 更多