在switch语句外声明全局变量

本文关键字:声明 全局变量 语句 switch | 更新日期: 2023-09-27 18:22:37

我想在switch语句之外声明一个全局变量,其中生成的记录可以来自两个不同的表。我怎样才能最好地做到这一点?

var q;
Switch(petType)
{
case 1:
    var q = from c in Cats
                where c.Type equals == 1
                select c;
     break;
case 2:
    var q = from d in Dogs 
                where d.Type equals == 1
                select d; 
     break;
 }
foreach(var r in q)
{
    //Do Stuff
}

在switch语句外声明全局变量

您在3个地方定义了"var q"。仅在一个地方需要。使用对象而不是var,就像下面的一样

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Dog> Dogs = new List<Dog>();
            List<Cat> Cats = new List<Cat>();
            object q;
            int petType = 1;

            switch(petType)
            {
            case 1:
                q = from c in Cats
                            where c.Type == 1
                            select c;
                 break;
            case 2:
                q = from d in Dogs 
                            where d.Type == 1
                            select d; 
                 break;
             }
        }
    }
    public class Cat
    {
        public int Type { get; set; }
    }
    public class Dog
    {
        public int Type { get; set; }
    }
}
​

详细说明@B.K.的建议,以防OP仍然不清楚。

public abstract class Animal {
   public int NoOfLegs { get; set; } // example
}
public class Cat : Animal {
}
public class Dog : Animal {
}
List<Animal> q;
Switch(petType)
{
   case 1:
   q = from c in Cats
       where c.Type equals == 1
       select c;
   break;
   case 2:
   q = from d in Dogs 
       where d.Type equals == 1
       select d; 
   break;
}
foreach(var r in q)
{
    //Do Stuff
}