有条件地定义变量类型C# [英] Define variable type conditionally C#

查看:149
本文介绍了有条件地定义变量类型C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

或者这个:

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

有办法吗?

推荐答案

一种选择是定义抽象,并在需要访问表时使用它们.

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

在表上实现接口

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

这篇关于有条件地定义变量类型C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆