我有两个自动生成的类,即 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;
知道如何做吗?
最佳答案
规范的解决方案是确保 Type1
和 Type2
都实现定义 MEMBER_1
、 MEMBER_2
等的通用接口(interface)。
由于技术原因您无法执行此操作,因此您有两种选择:
创建包装类型:创建一个新类
Type1WithInterface
,它具有与Type1
相同的成员,但也实现了上述通用接口(interface)。Type1WithInterfaces
在其构造函数中获取Type1
实例,并将每个属性访问传递给底层Type1
。或者,您可以使用
dynamic
keyword 。它禁用成员访问的编译时类型检查。
选项 1 的缺点是您必须编写大量样板代码,但优点是您将保留类型安全性。使用选项 2,所有类型安全赌注都将被关闭,拼写错误将在运行时而不是编译时困扰您。
关于c# - C# 中的 var 支持 Type1 或 Type2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72472644/