简体   繁体   English

传递null为空?

[英]Passing null for a short?

I have the following method: 我有以下方法:

    //returns -1 on failure
    public static int Add(
        string name, string email, string password, short defaultNumWeek)
    {
        KezberPMDBDataContext db = new KezberPMDBDataContext();
        Employee employee = new Employee 
        { 
            EmployeName = name,
            EmployeEmail = email,
            EmployePassword = password,
            DefaultNumWeek = defaultNumWeek
        };
        db.Employees.InsertOnSubmit(employee);
        try
        {
            db.SubmitChanges();
        }
        catch (Exception)
        {
            return -1;
        }

        return employee.EmployeID;
    }

The last parameter is optional and can be null in the database. 最后一个参数是可选的,在数据​​库中可以为null。 How can I do this without creating 2 separate methods? 如何在不创建两个单独方法的情况下执行此操作? I have other ones that are less simple. 我还有其他不那么简单的东西。 How can I pass a base type as null? 如何将基类型作为null传递?

Use Nullable type as 使用Nullable类型作为

public static int Add(
        string name, string email, string password, short? defaultNumWeek)

DefaultNumWeek property of Employee mast be Nullable too. Employee mast的DefaultNumWeek属性也可以为Nullable

static void Bar(Nullable<short> s)
{

}

or 要么

static void Bar(short? s)
{

}

The former is merely a short hand, see Using Nullable Types 前者只是一个简短的手,请参阅使用Nullable Types

Change the definition to: 将定义更改为:

public static int Add(
        string name, string email, string password, short? defaultNumWeek = null)

This allows you to call the same function while omitting the defaultNumWeek parameter. 这允许您在省略defaultNumWeek参数的同时调用相同的函数。

只要传递它,如果它为空则不要使用它。

You can handle this with Nullable Types . 您可以使用Nullable Types处理此问题。 C# has an alias where you attach a question mark (?) to a struct type (like short). C#有一个别名,您可以在其中将问号(?)附加到结构类型(如short)。

This allows you to compare it against null, ask whether it has a value and so forth. 这允许您将其与null进行比较,询问它是否具有值等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM