C# 有条件地定义变量类型#

C# 有条件地定义变量类型#,c#,var,implicit-typing,C#,Var,Implicit Typing,在“ADO.NET实体数据模型”中,我从许多表中创建了“数据库优先”模型。 所有表都有“代码”和“名称”字段以及不同的其他字段集。 然后我创建了一个“上下文”对象。 现在我想创建一个变量“src_table”,它将有条件地分配给context.table1或context.table2等,然后使用src_table.code和src_table.name属性 这样的代码很好用: var context = new postgresEntities(); var src_table = conte

在“ADO.NET实体数据模型”中,我从许多表中创建了“数据库优先”模型。 所有表都有“代码”和“名称”字段以及不同的其他字段集。 然后我创建了一个“上下文”对象。 现在我想创建一个变量“src_table”,它将有条件地分配给context.table1或context.table2等,然后使用src_table.code和src_table.name属性

这样的代码很好用:

var context = new postgresEntities();
var src_table = context.table1;
foreach (var src_table_rec in src_table)
{
  Console.WriteLine("Code: {0}, Name: {1}", src_table_rec.code, src_table_rec.name);
}
或者这个:

var context = new postgresEntities();
var src_table = context.table2;
foreach (var src_table_rec in src_table)
{
  Console.WriteLine("Code: {0}, Name: {1}", src_table_rec.code, src_table_rec.name);
}
但我不知道如何给选择表格的机会:

var context = new postgresEntities();

Console.WriteLine("Enter the table number:");
string response = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(response, out n);

if (isNumeric && n==1)
{
  var src_table = context.table1;
} 
else if (isNumeric && n==2)
{
  var src_table = context.table2;
} 
else
{
  Console.WriteLine("Table number {0} doesn't exist.", n);
}

foreach (var src_table_rec in src_table)
{
  Console.WriteLine("Code: {0}, Name: {1}", src_table_rec.code, src_table_rec.name);
}

有办法吗?

一个选项是定义抽象,并在需要访问表时使用这些抽象

public interface ITable {
    string code { get; set; }
    string name { get; set; }
}
在表上实现接口

public class Table1: ITable {
    public string code { get; set; }
    public string name { get; set; }
}

public class Table2: ITable {
    public string code { get; set; }
    public string name { get; set; }
}
并使用它们

var context = new postgresEntities();

Console.WriteLine("Enter the table number:");
string response = Console.ReadLine();
int n;
bool isNumeric = int.TryParse(response, out n);

ITable src_table = null;

if (isNumeric && n==1) {
    src_table = context.table1;
} else if (isNumeric && n==2) {
    src_table = context.table2;
} else {
  Console.WriteLine("Table number {0} doesn't exist.", n);
}

Console.WriteLine("Code: {0}, Name: {1}", src_table.code, src_table.name);

您可以使用
dynamic
type,但我不确定您在这里想要实现什么?不知道您想要做什么,但是如果您试图引用一个超出其范围的变量,您需要将src_表声明在您的表之外,这根本不起作用。我认为您试图通过继承、接口、反射或
dynamic
,而不是
var
来实现。