C# 如何定义泛型接口where子句的约束
C#没有预处理,我不想为所有需要此约束的接口定义“struct、IComparable、IFormattable、IConvertible”。我需要的是: 命名约束“IMyItemConstraint”用于几个通用接口,其中子句:C# 如何定义泛型接口where子句的约束,c#,.net,generics,cs0246,C#,.net,Generics,Cs0246,C#没有预处理,我不想为所有需要此约束的接口定义“struct、IComparable、IFormattable、IConvertible”。我需要的是: 命名约束“IMyItemConstraint”用于几个通用接口,其中子句: public interface IProperty2Enum<T> : IEnumerable<T> where T : IMyItemConstraint { } // <--- here public interf
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
公共接口IProperty2Enum
:IEnumerable
其中T:IMyItemConstraint{}/不幸的是,您不能继承泛型约束。您需要为每个类型参数分别定义约束。谢谢。:-)是否有编译器扩展或c#预处理器可用于解决这个(常见的?)问题?@Torstenstrull据我所知并不多。因为“4文本”、“Roslyn CTP”或其他自定义特定扩展似乎是唯一的解决方案,我接受了这个答案。谢谢。我会为锅炉板代码创建一个。另请参见:.@TnTinMn:好主意,如果您不在“概念”的项目阶段,您希望获得决策并尝试几种变体。如果您需要动态代码生成来快速评估备选方案,那么设置T4模板可能值得一试。请参阅:。这基本上是生成代码文件的预处理步骤。谢谢!
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 { }