如何将属性映射传递给此方法?
How can I pass a mapping of properties to this method?
public static SelectOption ToSelectOption(this BaseDomainEntity entityModel) {
return new SelectOption {
Id = entityModel.DomainId,
Name = entityModel.Name
};
}
此方法在我们的整个应用程序中用于创建 select 选项。大多数时候,每个模型都包含 id 和 name 作为我们要使用的字段。但是,有时,我们可能不得不使用 Id 和 ProductNumber 或 Id 和 Description 等。有没有一种方法可以为我的函数传递一个映射?
我什至不知道从哪里开始,但从概念上讲,就像
Id => entity.ProductNumber
Name => entity.Description
这样我就不必每次都需要一些与常用方法不同的东西时编写新函数。我想在不传递 属性 名称和使用反射的情况下执行此操作。
我不确定这些代码对您来说是否太多,但请参阅下文。
public static SelectOption ToSelectOption(this BaseDomainEntity entityModel, Func<BaseDomainEntity, SelectOption> selector)
{
return selector(entityModel);
}
用法如下
var option = instance.ToSelectOption(x => new SelectOption { Id = x.DomainId, Name = x.Name});
public static SelectOption ToSelectOption(this BaseDomainEntity entityModel) {
return new SelectOption {
Id = entityModel.DomainId,
Name = entityModel.Name
};
}
此方法在我们的整个应用程序中用于创建 select 选项。大多数时候,每个模型都包含 id 和 name 作为我们要使用的字段。但是,有时,我们可能不得不使用 Id 和 ProductNumber 或 Id 和 Description 等。有没有一种方法可以为我的函数传递一个映射?
我什至不知道从哪里开始,但从概念上讲,就像
Id => entity.ProductNumber
Name => entity.Description
这样我就不必每次都需要一些与常用方法不同的东西时编写新函数。我想在不传递 属性 名称和使用反射的情况下执行此操作。
我不确定这些代码对您来说是否太多,但请参阅下文。
public static SelectOption ToSelectOption(this BaseDomainEntity entityModel, Func<BaseDomainEntity, SelectOption> selector)
{
return selector(entityModel);
}
用法如下
var option = instance.ToSelectOption(x => new SelectOption { Id = x.DomainId, Name = x.Name});