【问题标题】:C# Interface determine implementationC#接口决定实现
【发布时间】:2021-06-15 15:17:30
【问题描述】:

我从数据库接收数据。从现在开始,一次只有一个模型,我称之为currentModel。接收到的模型类型必须在运行时确定。因此,我为模型IDataModel 实现了一个接口。每个可能的模型都实现IDataModel。有一个变量保存currentModel。为了使其通用,我将其定义为IDataModel。这是到目前为止的代码。

public async Task<List<T>> LoadData<T, U>(string sql, U parameters, string connectionString)
{
    using (IDbConnection connection = new SqlConnection(connectionString))
    {
        var rows = await connection.QueryAsync<T>(sql, parameters);

        return rows.ToList();
    }
}

private IDataModel currentModel;
private List<IDataModel> queryResult;

if (someCondition)
{
    currentModel = newSpecificModel();
    sql = someQuery;
}
else ....

queryResult = await _data.LoadData<IDataModel, dynamic>(sql, new {}, config.GetConnectionString("default"));

if (queryResult.Count == 1)
{
    currentModel= queryResult.First();
}
else
{
    // Do error handling here if more than one row is returned from the query
}

现在当我尝试访问某些属性时出现错误:IDataModel does not contain a definition for someProperty

currentModel.someProperty

如何在运行时确定当前的实现? 我的意思是我可以为每个可能的模型创建一个变量。但是有没有更优雅的方式呢?

编辑

将问题归结为这不起作用:

List<Interface> = List<Implementation>

见this post。

有什么方法可以解决这个问题?

【问题讨论】:

  • 我如何在运行时确定当前的实现?它会给你什么? ...您的错误是编译时错误而不是运行时...它someProperty 对所有IDataModel 都很常见,然后将其移至IDataModel ...如果不是...您必须为不同的类编写不同的代码

标签: c# linq


【解决方案1】:

看看curiously recurring template pattern;它对于创建具有正确类型的子对象很有用。 或许也可以看看this discussion。

【讨论】:

  • 请不要在没有先将重要内容放在答案中的情况下链接到外部资源。答案中的链接只能提供支持性证据。
  • 嗯,模式的名称是这里的真实信息,我认为没有必要总结。此外,链接的 SO 问题/答案可以完成这项工作。
  • 不,一点也不。您真的应该注意那些拥有大量代表的人 - 我们知道如何帮助您获得更多代表。
  • 那不是动力,只是让我觉得自己被宠坏了。
猜你喜欢
  • 2018-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多