【问题标题】:How to define constraint for generic interface where-clause如何为通用接口 where-clause 定义约束
【发布时间】:2017-04-12 20:56:41
【问题描述】:

C# 没有预处理,我不想为所有需要此约束的接口定义“struct、IComparable、IFormattable、IConvertible”。我需要的是这样的:

命名约束 "IMyItemConstraint" 用于几个通用接口 where 子句:

public interface IProperty2Enum<T>
    : IEnumerable<T>
    where T : IMyItemConstraint { } // <--- here

public interface IMyCollection2<T>
    : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged 
    where T : IMyItemConstraint { } // <--- here

public interface IMyObservableCollection2<T>
    : IEnumerable<T>, INotifyCollectionChanged, INotifyPropertyChanged 
    where T : IMyItemConstraint { } // <--- here

我尝试定义名称“IMyItemConstraint”,但出现错误 CS####:

public interface IMyItemConstraint 
    : struct, IComparable, IFormattable, IConvertible { } // CS1031: Type expected 

public interface IMyItemConstraint : where IMyItemConstraint
    : struct, IComparable, IFormattable, IConvertible { } // CS1031: Type expected 

public interface IMyItemConstraint<T> where T // This does not help:
    : struct, IComparable, IFormattable, IConvertible { }

是否可以为多个接口(合同)的通用接口 where 子句定义命名约束?

【问题讨论】:

标签: c# .net generics cs0246


【解决方案1】:

很遗憾,您不能继承通用约束。您需要为每个类型参数单独定义约束。

【讨论】:

  • 谢谢。 :-) 是否有可用的编译器扩展或 c# 预处理器来解决这个(常见的?)问题?
  • @TorstenCrull 据我所知。
  • 因为“4 Text”、“Roslyn CTP”或其他自定义特定扩展似乎是唯一的解决方案,我接受了这个答案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-22
  • 2017-08-28
  • 1970-01-01
  • 1970-01-01
  • 2011-01-13
  • 1970-01-01
相关资源
最近更新 更多