【发布时间】:2017-04-13 22:16:40
【问题描述】:
我想建立一套方法:
我有这个摘要:
public abstract Filter<T> Create(T type, string value);
public abstract IEnumerable<Filter<T>> Create(T type, IEnumerable<object> values);
及实施:
public override Filter<DiscountFilterType> Create(DiscountFilterType type, string value)
=> new DiscountFilter {Type = type, Value = string.IsNullOrWhiteSpace(value) ? null : value};
public override IEnumerable<Filter<DiscountFilterType>> Create(DiscountFilterType type, IEnumerable<object> values)
=> values.Select(value => this.Create(type, value?.ToString())).ToList();
看起来不错,但如果我想做这样的事情:
var type = DiscountFilterType.CampaignStatus;
var values = new List<CampaignStatus>{
CampaignStatus.Active,
CampaignStatus.Accepted,
CampaignStatus.Supplement};
// Act
var result = sut.Create(ype, values);
它试图将数组发送到字符串方法。
'CS1503 Argument 2: cannot convert from 'System.Collections.Generic.List<CampaignStatus>' to 'string'
发生了什么事? 如果我想这样做:
public abstract Filter<T> Create(T type, object value);
public abstract IEnumerable<Filter<T>> Create(T type, IEnumerable<object> values);
怎么样?
@编辑: 我想有一种方法来创建过滤器,它需要: 1. 一种类型,一种价值 2.一种类型,多个值,返回多个过滤器 3.多类型多值并返回多个过滤器
类型总是一些枚举,最后的值应该是字符串,但我不想在调用方法之前将值/数组转换为 ToString。
【问题讨论】:
-
@DavidG 所说的。最重要的是,您的通用方法似乎有点奇怪。也许退后一步,描述一下你打算做什么?
-
只有英文版
-
您的
List<CampaignStatus>不能分配给IEnumerable<object>,因此编译器正在回退到T, string重载。 -
快速解决方法是将您的方法签名更改为
Create(DiscountFilterType type, IEnumerable<T> values)