小编Rub*_*922的帖子

使用Python中的字典调用带参数的函数

我正在制作一个程序,它有一个主菜单,要求用户输入一个选项并将其存储在整数中option1,这在字典中查找options.然后运行相应的功能.如果函数没有参数,则以下代码有效:

options = {0 : FunctionZero,    # Assign functions to the dictionary
            1 : FunctionOne,
            2 : FunctionTwo,
            3 : FunctionThree}

options[option1]()    # Call the function
Run Code Online (Sandbox Code Playgroud)

如果函数有参数,上面的代码不起作用,因为该()部分假定函数没有参数,但我尝试了以下内容,它将函数的名称和参数存储在字典中的元组中:

options = {0 : (FunctionZero,""),    # FunctionsZero, FunctionOne
            1 : (FunctionOne,""),    # and FunctionTwo have no parameters
            2 : (FunctionTwo,""),
            3 : (FunctionThree,True)}    # FunctionThree has one parameter

if options[option1][1] == "":    # Call the function
    options[option1][0]()
else:
    options[option1][0](options[option1][1])
Run Code Online (Sandbox Code Playgroud)

这段代码似乎工作正常,但我想知道是否有更好的方法来做到这一点,特别是如果函数需要几个参数?在像C#这样的其他语言中,我可能会使用switch或case语句(不在Python中)而且我避免使用if...elif语句.

python parameters dictionary function

6
推荐指数
2
解决办法
1万
查看次数

在C#中,我应该按值传递参数并返回相同的变量,或者通过引用传递?

在C#程序中,我创建了一个从列表中删除对象的方法.用户输入要删除的项目的索引,然后要求用户确认删除,如果用户确认,则从列表中删除该项目,否则列表保持不变.
我不确定将参数传递给方法的最佳方法.我尝试通过引用传递列表(作为out参数):

static void DeleteCustomer(out List<Customer> customers)
{
    // ...display list of objects for user to choose from...
    int deleteId = ReadInt("Enter ID of customer to delete: ");
    Console.Write("Are you sure you want to delete this customer?");
    if (Console.ReadLine().ToLower() == "y")
    {
        customers.RemoveAt(deleteId);
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,因为我得到错误使用未分配的本地变量'customers'和out参数'customers'必须在控制离开当前方法之前分配.我以为我可以按值传递列表并返回相同的列表,如下所示:

static List<Customer> DeleteCustomer(List<Customer> customers)
{
    int deleteId = ReadInt("Enter ID of customer to delete: ");
    Console.Write("Are you sure you want to delete this customer?");
    if (Console.ReadLine().ToLower() == "y") …
Run Code Online (Sandbox Code Playgroud)

c# methods pass-by-reference pass-by-value argument-passing

6
推荐指数
1
解决办法
1559
查看次数

在 C# 中,如果将列表中的对象添加到另一个列表中,更改第二个列表中的对象是否会更改第一个列表中的相同对象?

假设我有一个名为的Person对象列表( List<Person>) persons,如下所示:

class Person
{
    public int PersonId { get; set; } // Unique ID for the person loaded from database
    public string Name { get; set; }
}

// In a different class
public List<Person> Persons = new List<Person>(); // Person objects are subsequently added to the list
Run Code Online (Sandbox Code Playgroud)

然后我Person从列表中选择一些对象,按属性(例如,按每个人的唯一 ID PersonId)对它们进行排序,然后将这些选定的Person对象添加到另一个名为 的列表中selectedPersons。
我现在需要编辑的属性Person对象,它是在selectedPersons,但需要这个的正本作出这些改变Person对象persons。我目前只知道selectedPersons列表中此人的索引,所以我可以简单地编辑selectedPersons列表中的人并将对该人所做的更改反映在原始persons …

c# list object reference-type

2
推荐指数
1
解决办法
1957
查看次数