3

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. 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?

4

5 回答 5

9

Use Nullable type as

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

DefaultNumWeek property of Employee mast be Nullable too.

于 2013-01-15T21:03:57.493 回答
3
static void Bar(Nullable<short> s)
{

}

or

static void Bar(short? s)
{

}

The former is merely a short hand, see Using Nullable Types

于 2013-01-15T21:04:24.367 回答
3

将定义更改为:

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

这允许您在省略defaultNumWeek参数的同时调用相同的函数。

于 2013-01-15T21:05:38.860 回答
0

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

于 2013-01-15T21:05:05.883 回答
0

您可以使用Nullable Types处理此问题。C# 有一个别名,您可以在其中将问号 (?) 附加到结构类型(如 short)。

这允许您将它与 null 进行比较,询问它是否有值等等。

于 2013-01-15T21:05:07.583 回答