简体   繁体   English

通用约束:强制类型具有静态函数和带参数的构造函数

[英]Generic constraint: Enforce type to have static function and constructor with parameters

I know you can write: 我知道你可以写:

class GenericClass<T> where T : new()
{ 

}

to enforce that T has an empty constructor. 强制执行T有一个空构造函数。

My Qs are : 我的Qs是:

  1. can you enforce that T has a constructor with a specific type of parameter? 你能强制说T有一个具有特定参数类型的构造函数吗? Like: 喜欢:

     class SingletonFactoryWithEmptyConstructor<T> where T : new(int) 
  2. can you enforce that T has a static function (let's say, void F() ) so that you can use this function inside the generic class? 你能强制执行T有一个静态函数(比方说, void F() ),这样你就可以在泛型类中使用这个函数吗? Like : 喜欢 :

     class GenericClass<T> where T : void F() { void G () { TF(); } } 

    I know you can specify that T implements an interface but I don't want that. 我知道你可以指定T实现一个接口,但我不希望这样。 I want to specify that T has a static function. 我想指定T具有静态函数。

No, there's nothing like this in C#. 不,在C#中没有这样的东西。

I've previously suggested that "static interfaces" could express this reasonably neatly. 我之前曾建议“静态接口”可以合理地表达这一点。 They'd only be useful for generic type constraints (I suspect, anyway) but then you could express: 它们对泛型类型约束有用(我怀疑,无论如何)但是你可以表达:

  • Constructors with arbitrary parameters 具有任意参数的构造函数
  • Static methods and properties 静态方法和属性
  • Operators 运营商

The last of these points is particularly interesting in my view, allowing things like a generic "Average" method over numeric types with suitable addition and division operators. 在我看来,这些要点中的最后一点特别有趣,允许使用具有合适的加法和除法运算符的数字类型的通用“平均”方法。

I believe some folks at MS have thought about something similar, but I haven't heard anything to suggest they're actively working on it. 我相信MS的一些人已经考虑过类似的东西,但我没有听到任何暗示他们正在积极研究的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 您可以对多个泛型类型参数实施相同的约束吗? - Can you enforce the same constraint on multiple generic type parameters? 有没有办法在没有通用约束的情况下强制执行无参数构造函数 - Is there a way to enforce parameterless constructor without generic constraint 限制泛型类型参数以具有特定构造函数 - Restricting a generic type parameters to have a specific constructor C#泛型方法,在new()构造函数约束中输入参数 - C# generic methods, type parameters in new() constructor constraint 具有新类型约束的泛型构造函数 - Generic constructor with new type constraint C#。 是否可以使用具有基类型约束的静态泛型类,该基类型约束具有带有进一步基类型约束的方法 - C#. Is is possible to have a static generic class with a base type constraint that has a method with a further base type constraint 如何使用泛型类型约束来强制 Add 方法存在 - How to use generic type constraint to enforce Add method existence 通用类型约束构造函数的限制,需要咨询 - Generic type constraint constructor limitation, need advice 泛型类型的构造函数约束还是只是在我的泛型类型构造函数中检查约束? - Constructor constraint on generic types or simply check for constraint within my generic type constructor? 映射使用Automapper接收构造函数参数的泛型类型 - Map generic type that receives constructor parameters with Automapper
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM