在两种不同的方法中使用字符串

时间:2012-07-03 13:56:40

标签: c# windows-phone-7

我一直在尝试将字符串值从一个方法传递到另一个方法。这是我的两种方法。

方法1 -

public void listBox1_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count > 0)
    {
        var c_id = (e.AddedItems[0] as Foodlist).C_ID;
        string listboxid = c_id.ToString();
    }
}

我想在第二种方法中使用字符串listboxid值,以便我可以将其用于比较 方法2 -

public void deletemyfood()
{
    using (FoodDataContext context = new FoodDataContext(Con_String))
    {
        string listboxindex = listboxid;
        IQueryable<FoodViewModel> foodQuery = from c in context.FoodTable where c.C_ID.ToString() == listboxindex select c;
        ....
    }
}

任何想法或建议?

1 个答案:

答案 0 :(得分:2)

以下是关于如何使用返回值和参数的简单示例:

class Program
{
    static void Main(string[] args)
    {
        var result = Method1("Test");
    }

   static string Method1(string input)
   {
       return string.Format("I got this input: {0}", input);
   }
}

在此示例中,方法Method1接受一个字符串参数,然后返回一个字符串。

在您的情况下,您可能希望将DeleteMyFood的方法签名更改为:

public void DeleteMyFood(string foodId)

如果你想要某种结果,也知道方法何时成功,你也可能希望从该方法返回一个值。这可以通过再次修改方法签名来完成:

public bool DeleteMyFood(string foodId)

如果我根据您的评论正确理解,您希望将事件处理程序更改为:

public void listBox1_SelectionChanged(object sender,
                                    System.Windows.Controls.SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count > 0)
    {
        var c_id = (e.AddedItems[0] as Foodlist).C_ID;
        string listboxid = c_id.ToString();
        DeleteMyFood(listboxid);
    }
}

这要求方法DeleteMyFood接受string类型的参数,所以我们也需要更改它:

public void deletemyfood(string foodId)
{
    using (FoodDataContext context = new FoodDataContext(Con_String))
    {
        string listboxindex = listboxid;
        IQueryable<FoodViewModel> foodQuery = from c in context.FoodTable where c.C_ID.ToString() == foodId select c;
        // .. rest of code here ..
    }
}