是否支持非泛型类中的泛型构造函数? [英] Is generic constructor in non-generic class supported?
问题描述
是不是不支持,是不是支持但是我要搞点花样?
Is it not supported, is it supported but I have to do some tricks?
示例:
class Foo
{
public Foo<T1,T2>(Func<T1,T2> f1,Func<T2,T1> f2)
{
...
}
}
泛型仅在构造函数中使用,没有依赖于它们的字段/属性,我使用它(泛型)来强制 f1 和 f2 的类型相关.
the generics are only used in constructor, there is no field/property depended on them, I use it (generics) to enforce the type correlation for f1 and f2.
备注:我找到了解决方法 -- 静态方法 Create,但无论如何我很好奇为什么我的直接方法有问题.
Remark: I found the workaround -- static method Create, but anyway I am curious why I have problem with straightforward approach.
推荐答案
不,泛型或非泛型类都不支持泛型构造函数.同样,不支持通用事件、属性和终结器.
No, generic constructors aren't supported in either generic or non-generic classes. Likewise generic events, properties and finalizers aren't supported.
只是偶尔我同意它会很方便 - 但语法看起来很糟糕.例如,假设您有:
Just occasionally I agree it would be handy - but the syntax would look pretty awful. For example, suppose you had:
public class Foo<T> {}
public class Foo
{
public Foo<T>() {}
}
什么会
new Foo<string>()
做什么?调用非泛型类的泛型构造函数,还是泛型类的普通构造函数?你必须以某种方式区分它们,这会很混乱:(
do? Call the generic constructor of the non-generic class, or the normal constructor of the generic class? You'd have to differentiate between them somehow, and it would be messy :(
同样,考虑泛型类中的泛型构造函数:
Likewise, consider a generic constructor in a generic class:
public class Foo<TClass>
{
public Foo<TConstructor>() {}
}
你会如何调用构造函数?希望我们都同意:
How would you call the constructor? Hopefully we can all agree that:
new Foo<string><int>()
太丑了...
所以,是的,从语义上讲,它偶尔会有用 - 但不幸的是,由此产生的丑陋抵消了这一点.
So yes, semantically it would be occasionally useful - but the resulting ugliness counterbalances that, unfortunately.
这篇关于是否支持非泛型类中的泛型构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!