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

本小妞迷上赌 提交于 2019-12-06 05:29:04

问题


I know you can write:

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

}

to enforce that T has an empty constructor.

My Qs are :

  1. can you enforce that T has a constructor with a specific type of parameter? 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? Like :

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

    I know you can specify that T implements an interface but I don't want that. I want to specify that T has a static function.


回答1:


No, there's nothing like this in 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.



来源:https://stackoverflow.com/questions/5919773/generic-constraint-enforce-type-to-have-static-function-and-constructor-with-pa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!