我有這些類:顯式和隱投與泛型類型
public class FilterBackOfficeDiscountFilterType
{
public FilterBackOfficeDiscountFilterType();
public FilterBackOfficeDiscountFilterType(string filterValue = null, string filterType = null);
[JsonProperty(PropertyName = "filterType")]
public string FilterType { get; set; }
[JsonProperty(PropertyName = "filterValue")]
public string FilterValue { get; set; }
}
而我:
public abstract class Filter<T>
where T : struct
{
public T Type { get; set; }
public string Value { get; set; }
}
和:
public class DiscountFilter : Filter<DiscountFilterType>
{
}
我想投DiscountFilter
到FilterBackOfficeDiscountFilterType
在明確或隱含的方式。
所以我添加操作方法:
public class DiscountFilter : Filter<DiscountFilterType>
{
public static implicit operator FilterBackOfficeDiscountFilterType(DiscountFilter filter)
=> new FilterBackOfficeDiscountFilterType(filterType: filter.Type.ToString(), filterValue: filter.Value);
}
但它不會編譯,因爲:
Cannot implicitly convert type 'Filter<DiscountFilterType>' to 'FilterBackOfficeDiscountFilterType'
我可怎麼辦呢?
DiscountFilterType
是一個枚舉。
而且FilterCreator.Create是:
public class DiscountFilterCreator : FilterCreator<DiscountFilterType>
{
public override Filter<DiscountFilterType> Create(DiscountFilterType type, string value)
=> new DiscountFilter {Type = type, Value = string.IsNullOrWhiteSpace(value) ? null : value};
}
它派生自:
public abstract class FilterCreator<T>
where T : struct
{
public abstract Filter<T> Create(T type, string value);
}
而在去年Filter
是:
public abstract class Filter<T>
where T : struct
{
public T Type { get; set; }
public string Value { get; set; }
}
編輯 重現您有問題要做到這一點
DiscountFilter filter = new DiscountFilterCreator().Create(DiscountFilterType.normal, "wow");
編輯
DiscountFilter x = this.FilterCreator.Create(DiscountFilterType.BrandId, brandId);
FilterBackOfficeDiscountFilterType y = x;
編輯 它的工作原理:
DiscountFilter x = (DiscountFilter)this.FilterCreator.Create(DiscountFilterType.BrandId, brandId);
FilterBackOfficeDiscountFilterType y = x;
,但我想這樣做是這樣的:
FilterBackOfficeDiscountFilterType x = this.FilterCreator.Create(DiscountFilterType.BrandId, brandId);
所以我需要太多這樣的隱式轉換:
public class DiscountFilter : Filter<DiscountFilterType>
{
public static implicit operator DiscountFilter(Filter<DiscountFilterType> filter)
=> new DiscountFilter {Value = filter.Value};
public static implicit operator FilterBackOfficeDiscountFilterType(DiscountFilter filter)
=> new FilterBackOfficeDiscountFilterType(filterType: filter.Type.ToString(), filterValue: filter.Value);
}
但從derivered類基地隱式轉換是不允許的!
DiscountFilter.implicit operator DiscountFilter(Filter<DiscountFilterType>): user-defined conversions to or from a base class are not allowed
所有的代碼在這裏編譯(給定一些拼寫錯誤和重複的類型定義,但沒關係)。 –
你有沒有試過把這個操作符移動到泛型類? –
你不清楚你的問題,因爲你的代碼確實編譯得很好。 – Evk