【问题标题】:Abstract generic methods and string and ienumerable objects issue抽象泛型方法以及字符串和可枚举对象问题
【发布时间】: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&lt;CampaignStatus&gt;' 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&lt;CampaignStatus&gt; 不能分配给IEnumerable&lt;object&gt;,因此编译器正在回退到T, string 重载。
  • 快速解决方法是将您的方法签名更改为Create(DiscountFilterType type, IEnumerable&lt;T&gt; values)

标签: c# oop


【解决方案1】:

对于可枚举序列中的值的类型,您需要一个额外的通用参数(而不是使用object)。尝试以下抽象类型的定义:

public abstract Filter<TType, TValue> Create(TType type, TValue value);
public abstract IEnumerable<Filter<TType, TValue>> Create(TType type, IEnumerable<TValue> values);

然后您可以将 TValue 类型的实例转换为方法主体中的字符串(使用 ToString 如果这是您的约定所要求的,这部分有点超出您的问题范围)。

【讨论】:

  • 但是TValue可以是字符串、自定义类、日期时间和int。
猜你喜欢
  • 2022-01-15
  • 2011-11-16
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多