通用的限制:强制类型有静态的功能和构造函数参数 [英] Generic constraint: Enforce type to have static function and constructor with parameters

查看:128
本文介绍了通用的限制:强制类型有静态的功能和构造函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你可以这样写:

 类GenericClass< T>其中,T:新的()
{

}
 

要强制执行 T 有一个空的构造。

我的Qs的是:

  1. 你能强制执行 T 与参数的特定类型的构造?像:

     类SingletonFactoryWithEmptyConstructor< T>其中,T:新的(INT)
     

  2. 你能强制执行 T 有一个静态函数(比方说,无效F())这样就可以使用此功能的通用类里面?像:

     类GenericClass< T>其中,T:无效F()
    {
       无效G()
       {
           T.F();
       }
    }
     

    我知道你可以指定 T 实现一个接口,但我不希望出现这种情况。我想指定 T 有一个静态函数。

解决方案

没有,没有什么比这在C#。

我有previously建议<一href="https://msmvps.com/blogs/jon_skeet/archive/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces.aspx">"static 。接口会前preSS这个合理巧妙地他们会的只有的是泛型类型的限制有用的(我怀疑,反正),但是你可以EX preSS:

  • 构造任意参数
  • 静态方法和属性

最后这点,在我看来特别有意思,让像一个普通的平均的方法在数字类型用合适的加法和除法运算符。

我相信,一些人在MS曾经想过类似的东西,但我还没有听到任何消息表明他们正在积极努力就可以了。

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.

解决方案

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.

这篇关于通用的限制:强制类型有静态的功能和构造函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆