Define variable type conditionally C#

a 夏天 提交于 2021-02-05 11:55:28

问题


In "ADO.NET Entity Data Model" I have created a "database first" model from a number of tables. All tables have "code" and "name" fields and different set of other fields. Then I've created a "context" object. Now I want to create a variable "src_table", which will be assigned to context.table1 or context.table2 etc conditionally and then work with src_table.code and src_table.name properties.

A code like this works fine:

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);
}

Or this:

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);
}

But I have no idea how to give the opportunity to choose the table:

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);
}

Is there a way to do it?


回答1:


One option is to define abstractions and use those when you need to access the table.

public interface ITable {
    string code { get; set; }
    string name { get; set; }
}

Implement the interfaces on your tables

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; }
}

And use them

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);


来源:https://stackoverflow.com/questions/26420823/define-variable-type-conditionally-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!