我知道你可以这样写:
类GenericClass< T>其中,T:新的()
{
}
要强制执行 T
有一个空的构造。
我的Qs的是:
你能强制执行 T
与参数的特定类型的构造?像:
类SingletonFactoryWithEmptyConstructor< T>其中,T:新的(INT)
你能强制执行 T
有一个静态函数(比方说,无效F()
)这样就可以使用此功能的通用类里面?像:
类GenericClass< T>其中,T:无效F()
{
无效G()
{
T.F();
}
}
我知道你可以指定 T
实现一个接口,但我不希望出现这种情况。我想指定 T
有一个静态函数。
没有,没有什么比这在C#。
我有previously建议"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 :
can you enforce that T
has a constructor with a specific type of parameter? Like:
class SingletonFactoryWithEmptyConstructor<T> where T : new(int)
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 OperatorsThe 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.