c# - C# 中的 var 支持 Type1 或 Type2

标签 c# generics types var

我有两个自动生成的类,即 Type1 和 Type2。这些类中的每一个都处理其他相关的自动生成的类。由于它们是自动生成的,我无法将它们更改为使用抽象类或接口(interface)。 我有两种方法,一种返回 Type1,另一种返回 Type2。 Type1和Type2几乎相同,所以我想像下面这样调用它们以避免我这边的代码重复,当然它不起作用,因为需要在编译时知道类型。

var response = string.IsNullOrWhiteSpace(inputObject.HistoricYear) ? Type1: Type2;
if (string.IsNullOrWhiteSpace(inputObject.HistoricYear))
{
    response = TsiService.GetAccountTransactionsList(inputObject);
} else
{
    response = TsiService.GetAccountTransactionsHist(inputObject);
}

我还尝试使用对象,然后收到此错误对象不包含 MEMBER_1 和 MEMBER_2 等的定义:

var response = null;
if (string.IsNullOrWhiteSpace(inputObject.HistoricYear))
{
    response = TsiService.GetAccountTransactionsList(inputObject);
} else
{
    response = TsiService.GetAccountTransactionsHist(inputObject);
}

CustomObject.member1 = response.MEMBER_1;
CustomObject.member2 = response.MEMBER_2;

知道如何做吗?

最佳答案

规范的解决方案是确保 Type1Type2 都实现定义 MEMBER_1MEMBER_2 等的通用接口(interface)。

由于技术原因您无法执行此操作,因此您有两种选择:

  1. 创建包装类型:创建一个新类 Type1WithInterface ,它具有与 Type1 相同的成员,但也实现了上述通用接口(interface)。 Type1WithInterfaces 在其构造函数中获取 Type1 实例,并将每个属性访问传递给底层 Type1

  2. 或者,您可以使用 dynamic keyword 。它禁用成员访问的编译时类型检查。

选项 1 的缺点是您必须编写大量样板代码,但优点是您将保留类型安全性。使用选项 2,所有类型安全赌注都将被关闭,拼写错误将在运行时而不是编译时困扰您。

关于c# - C# 中的 var 支持 Type1 或 Type2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72472644/

相关文章:

C# .NET Core 如何在 System.Private.CoreLib.dll 中调试 System.IO.FileNotFoundException?

c# - 通用属性——如何在运行时指定类型

java - 关于java泛型的问题

c# - 为什么 Func<...> 和 Action 不统一?

javascript - Reactjs typescript : Property 'toLowerCase' does not exist on type 'never'

javascript - 这是一种确定对象是否为 JavaScript 数组的可接受方法吗?

c# - 如何将十进制数传递给 rest web 服务

c# - Windows 搜索 - 在 C# 中进行全文搜索

C#:如何让用户控件正确地自动调整自身大小

c# - 将 Func<T, string>[] 转换成 Func<T, string[]>?